假设我有以下代码:
var Foo = (function () {
//constructor
var Foo = function (callbackFunction) {
this.callbackFunction = callbackFunction;
};
//method
Foo.prototype = {
run: function () {
if (typeof(this.callbackFunction) === 'function') {
this.callbackFunction.call(???); //??? should be the object that created this Foo instance.
}
}
};
return Foo;
})();
这保存在foo.js
中我也有以下代码:
var Bar = (function () {
//constructor
var Bar = function (v1, v2) {
this.v1 = v1;
this.v2 = v2;
};
Bar.prototype.callback = function() {
//'this' should be the instance of Bar
console.log('value of v1 is ' + this.v1 + ' value of v2 is ' + this.v2);
}
Bar.prototype.callFoo = function() {
this.foo = new Foo(this.callback);
this.foo.run();
}
return Bar;
})();
var bar1 = new Bar('apple', 'orange');
bar1.callFoo();
var bar2 = new Bar('grape', 'banana');
bar2.callFoo();
再次保存在bar.js
内在foo内部,我有一行:this.callbackfunction.call(???);
因此,为了使这项工作,我必须将创建foo实例的对象传递给呼叫函数,但是如何?
我的建议是使用function.bind()
方法。
Mozilla开发人员网络:
bind()方法创建了一个新功能,当调用时, 此关键字设置为提供的值,给定的序列 在调用新功能时提供的任何提供的参数。
可能很难找到将bar传递到foo.callbackfunction的方法,但是如果bar通过this.callbackFunction.bind(this)
传递,那么FOO可以在不经过参数的情况下调用this.callbackFunction()
(或使用call
)
还有一些JavaScript库可以让您在较旧的浏览器中进行此操作,因为bind()
是一个相对较新的功能。例如,在Dojo中,称为hitch()
。