用"this"调用函数

str*_*ger 11 javascript

我有一个<a>元素的onclick处理程序(实际上,它是一个jQuery创建的处理程序,但这并不重要).它看起来像这样:

function handleOnClick() {
    if(confirm("Are you sure?")) {
        return handleOnClickConfirmed();
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

通过此函数,可以在单击<a>元素时访问对象.但是,handleOnClickConfirmed 是一个Window元素!我想handleOnClickConfirmed具有相同的是handleOnClick一样.我该怎么做?

(我知道我可以将作为handleOnClickConfirmed的参数传递,但我的一些代码已经使用了handleOnClickConfirmed,我不想重写那些调用.此外,我认为使用看起来更干净.)

Rob*_*Rob 26

以下应该这样做:

function handleOnClick() {
    if( confirm( "Sure?" ) ) {
        return handleOnClickConfirmed.call( this );
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

call()附加到Function对象的功能旨在允许这样做; 调用具有所需上下文的函数.在设置调用其他对象中的函数的事件处理程序时,这是一个非常有用的技巧.


Ben*_*nry 11

Rob的答案是您问题的最佳答案,但我想解决您在原始问题中所写的内容:

我知道我可以将此作为handleOnClickConfirmed的参数传递,但我的一些代码已经使用handleOnClickConfirmed,我不想重写这些调用.

就解释器而言,JavaScript参数始终是可选的.例如,如果你有这个功能:

function MyFunction(paramA, paraB) {
  // do nothing
}
Run Code Online (Sandbox Code Playgroud)

所有这些调用都将执行而不会出现错误:

MyFunction(1,2);
MyFunction(1);
MyFunction();
Run Code Online (Sandbox Code Playgroud)

因此,您可以修改handleOnClickConfirmed以接受本质上是可选参数的内容.像这样:

function handleOnClickConfirmed(context) {
  context = context || this;
  // use context instead of 'this' through the rest of your code
}
Run Code Online (Sandbox Code Playgroud)

同样,在这种特殊情况下,呼叫功能是最佳解决方案.但是我在上面概述的技术在您的工具箱中是一个很好的技术.