开发者

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

开发者 https://www.devze.com 2023-03-13 09:49 出处:网络
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:

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

精彩评论

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