我什么时候应该使用call()vs直接调用函数?

bul*_*ley 14 javascript unobtrusive-javascript

我有一个使用大量回调的JavaScript应用程序.典型的函数将进行回调,并使用另一个回调进行包装.

Namespace.foo = function( arg, their_on_success ) {
    var my_on_success = function( result ) {
        console.log( 'my_on_success() called' );
        if( 'function' === typeof their_on_success ) {
              their_on_success( result );
        }
    }
    something( arg, my_on_success );
};
Run Code Online (Sandbox Code Playgroud)

鉴于以上示例,何时应该使用本机call()方法(将结果var作为第二个参数their_on_success()传递)而不是通过函数调用来调用和传递结果?

Joe*_*Joe 19

call()用于更改函数的this值:

var obj = {a: 0};
method.call(obj, "parameter");
function method(para) {
    this.a == 0; // true <-- obj is now this
}
Run Code Online (Sandbox Code Playgroud)


Roc*_*mat 7

使用call(或apply)的唯一原因是如果要设置this函数内部的值.

好吧,我猜apply在其他情况下可能很有用,因为它接受一系列参数.