我正在尝试为一个对象编写 OO javascript,该对象具有昂贵的初始化过程,完成后会回调一个函数。
问题在于调用者需要在回调例程中使用同一对象的函数,而该对象尚不存在:
// ctor for foo object
function foo(callback) {
// do slow initialization here..
// callback when done
callback();
};
foo.prototype = function() {
return {
// doStuff method
doStuff: function() {
alert('stuff done');
}
};
}();
// instantiate the foo object, passing in the callback
var f = new foo(function() {
//Uncaught TypeError: Cannot call method 'doStuff' of undefined
f.doStuff();
});
jsFiddle 我在这里缺少什么?
最佳答案
这应该是一个简单的修复。首先,确保调用回调时将 this
对象设置为当前对象
function foo(callback) {
// do slow initialization here..
callback.call(this);
};
然后调整你的回调方式
var f = new foo(function() {
this.doStuff();
});
这是你的 updated fiddle
关于Javascript:构造函数中的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999951/