简体   繁体   中英

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, everything 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()});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM