Javascript回调与对象结构 [英] Javascript Callbacks with Object contructor
问题描述
好的,这可能是JavaScript下的最愚蠢的问题。但我无能为力。下面是一个函数,创建和对象和调用回调(不是确切的代码,但类似的东西)。
Ok, this might be the stupidest question asked under JavaScript. But I am clueless. Following is a function which creates and object and call the callback (not the exact code but something similar).
myObject = function(callback){
var tmpThis = this;
this.accounts = [];
tmpThis.accounts[0] = 1;
tmpThis.accounts[1] = 2;
callback();
}
function caller(){
var newMyObject = new myObject(function() {
alert(newMyObject.accounts[1]);
});
}
newMyObject
未定义里面的回调函数。有没有办法我可以访问它。我读了类似的问题,但没有一个解释为什么。
newMyObject
is undefined inside the callback function. Is there a way I can access it. I read similar questions but none simply explains why.
我可以通过将创建的对象在第二个参数传回回调函数来修复它。
I can fix it by passing back the created object in a second parameter to the callback function. But I think its a hack rather than the proper way.
推荐答案
您可以使用 this
在新创建对象的上下文中访问回调,调用
来调用回调。
You can use this
to access the callback in the context of the newly create object, and call
to invoke the callback.
myObject = function(callback){
var tmpThis = this;
this.accounts = [];
tmpThis.accounts[0] = 1;
tmpThis.accounts[1] = 2;
callback.call(this);
}
function caller(){
var newMyObject = new myObject(function() {
alert(this.accounts[1]);
});
}
这篇关于Javascript回调与对象结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!