绑定实例方法与包装匿名函数



[这与Bound函数有关,而不是用于注入额外参数的闭包,但既没有明确询问也没有回答。]

我正在调用一个函数,该函数需要一个函数作为其参数。我想从我的类传递一个方法,绑定到我的类的一个实例。为了清楚起见,假设我的类看起来像:

var MyClass = function() {}
MyClass.prototype.myMethod = function() { ... }
var my_instance = new MyClass();

使用bind:有实质性区别吗

doSomething(my_instance.myMethod.bind(my_instance))

并将调用封装在一个匿名函数中:

doSomething(function() { my_instance.myMethod(); })

如果类中的原型需要生成回调,它可能不知道其实例的名称。因此,您需要使用this,但this的值取决于回调的执行位置。

考虑以下示例:

var MyClass = function (x) { this.something = x; };
MyClass.prototype.makeCall = function () {
    var myBadCallback  = function() { console.log(this.something); };
    var myGoodCallback = function() { console.log(this.something); }.bind(this);
    // When called, the value of "this" points to... we don't know
    callMeBack( myBadCallback );
    // When called, the value of "this" points to this instance
    callMeBack( myGoodCallback );
};

function callMeBack( callback ) { callback(); };
var foo = new MyClass('Hello World!');
var bar = new MyClass('Goodbye!');
// Probably prints "undefined", then prints "Hello World!"
foo.makeCall();
// Probably prints "undefined", then prints "Goodbye!"
bar.makeCall();

在上面的例子中,第一个输出可能打印undefined,因为上下文(this所指的)在回调执行时已经发生了变化。

这个例子可能看起来是人为的,但这类情况确实出现了,AJAX回调是一种常见的情况。

最新更新