开发者

Can a callback function that belongs to a JavaScript object prototype access the object members?

How can callback function that belong to a JavaScript object prototype access the object members? the callback can't be closure, ev开发者_如何学编程erything must be defined as follows:

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
}


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

.bind, ES5 shim for older browsers


In javascript this always points to the object on which the function is invoked or the global object if it's not invoked on anything. Can you do it this way?

Obji.prototype.func = function(){
   var ref = this;
   database.get("someKey", function(){ref.cb()});
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜