问题描述
|
属于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
}
解决方法
database.get(\"someKey\",this.cb.bind(this));
.bind
,适用于旧版浏览器的ES5填充
, 在javascript中,ѭ3始终指向在其上调用了函数的对象,或者指向未对任何对象进行调用的全局对象。你能这样吗?
Obji.prototype.func = function(){
var ref = this;
database.get(\"someKey\",function(){ref.cb()});
}