我正在尝试通过以下方式在匿名函数中访问对象的成员函数:
function a()
{
this.memb = 10;
}
a.prototype.hide_member = function(id){
alert(id);
}
a.prototype.show_member = function(){
setTimeout('this.hide_member(this.memb)', 2000); //Problem 1
setTimeout(this.hide_member(this.memb), 2000); //Problem 2
setTimeout(alert(this.memb), 2000); //Problem 3
this.memb++;
}
var obj = new a();
obj.show_member();
在这里,问题1-代码正好在给定的时间正确执行,意味着恰好在2000毫秒后执行,但是在2000毫秒后显示以下错误-
Uncaught TypeError: Object [object global] has no method 'hide_member'
(anonymous function)
问题2-代码正在执行,但是在代码解析后立即执行,这意味着没有在2000毫秒后执行。
问题3-与问题2相同的问题
我对这三个问题感到困惑。谢谢
这里发生了几件事情:
在此代码中:
setTimeout(this.hide_member(this.memb), 2000);
您正在立即调用 this.hide_member
,并将其返回值传递给setTimeout
。这是完全一样foo(bar())
,在那里你打电话 bar
,并通过其返回值成foo
。
您需要将一个函数传递到中setTimeout
,然后从该函数中调用成员函数。请注意,函数中的函数this
会有所不同,因此您必须记住它:
a.prototype.show_member = function(){
var self = this,
memb_to_hide = this.memb;
setTimeout(function() {
self.hide_member(memb_to_hide);
}, 2000);
this.memb++;
}
请注意,我还记得this.memb
该函数中使用的旧值。
另一种方法是使用ES5的Function#bind
,但它要求浏览器的JavaScript引擎具有该功能(或者您已加载“ ES5填充程序”,这bind
是可填充功能):
a.prototype.show_member = function(){
setTimeout(this.hide_member.bind(this, this.memb), 2000);
this.memb++;
}
Function#bind
返回一个函数,该函数在被调用时将使用您在第一个参数中给出的值调用原始函数this
(然后传递任何其他参数)。在这种情况下,我们不必记住旧值,this.memb
因为我们已经将旧值传递给了bind
。
旁注:您要依靠恐怖的自动分号插入功能。我建议不要这样做,并在语句的末尾提供分号,例如:
a.prototype.mumble = function() {
/*...*/
}; // <=== Note the ;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句