2

属于 JavaScript 对象原型的回调函数如何访问对象成员?回调不能关闭,一切都必须定义如下:

function Obji(param){
   this.element = param;
}

Obji.prototype.func(){
   database.get("someKey",this.cb);
}

Obji.prototype.cb(){
   //here I would like to access this.element
}
4

2 回答 2

5

database.get("someKey",this.cb.bind(this));

.bind, ES5 shim用于旧版浏览器

于 2011-06-14T16:53:15.883 回答
2

在 javascriptthis中,总是指向调用函数的对象或全局对象(如果它没有在任何东西上调用)。你可以这样做吗?

Obji.prototype.func = function(){
   var ref = this;
   database.get("someKey", function(){ref.cb()});
}
于 2011-06-14T16:47:02.527 回答