Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
属于JavaScript对象原型的回调函数能否访问对象成员?_Javascript_Prototype Programming_Serverside Javascript - Fatal编程技术网

属于JavaScript对象原型的回调函数能否访问对象成员?

属于JavaScript对象原型的回调函数能否访问对象成员?,javascript,prototype-programming,serverside-javascript,Javascript,Prototype Programming,Serverside Javascript,属于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 } 在javascript中,此始终指

属于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
}

在javascript
中,此
始终指向调用函数的对象,或者如果未在任何对象上调用函数,则指向全局对象。你能这样做吗

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


,对于较旧的浏览器

您需要对象的引用。在javascript中,函数和它被分配到的对象之间没有链接。所以除非你能通过闭包的方式偷运一份推荐信,f.i.,否则你没办法做你想做的事<代码>此
从不指函数被认为是其成员的对象,它总是指函数被调用的对象。@entonio我不确定你是对还是错,这就是为什么我问这个问题,似乎你错了,请查看@Raynos的回答否,我没有错
bind
是最近引入的一个函数(即并非在所有浏览器中都可用),在这种情况下,它的作用与我向您建议的
function(){ref.cb()}
相同。什么条件不允许您使用
function(){ref.cb()}
,但允许
bind
?(当然,调用
bind
会创建一个闭包。)@entonio bind可以得到更多优化。除此之外,一切都是一样的。(除此之外,您还可以进行curry绑定并将上下文设置为
null