[英]How to access a prototype's parent this from within a method's function
我有这个类/功能
function Menu()
{
this.closetimer = 0;
this.dropdown = 0;
}
Menu.prototype.menuTimer = function()
{
this.closetimer = setTimeout(function()
{
this.menuClose();
}, this.timeout);
}
Menu.prototype.menuClose = function()
{
if(this.dropdown) this.dropdown.css('visibility','hidden');
}
我想调用函数menuClose()
这是Menu类的一部分,但我认为这段代码实际上试图从closetimer
对象调用menuClose()
。
如何从menuClose()
中的Menu对象引用menuTimer()
?
在你的setTimeout()
回调中, this
指的是window
,只需保留这样的引用:
Menu.prototype.menuTimer = function(){
var self = this;
this.closetimer = setTimeout(function(){
self.menuClose();
}, this.timeout);
}
另一种方法是绑定内部函数。
Menu.prototype.menuTimer = function(){ this.closetimer = setTimeout(function(){ this.menuClose(); }.bind(this), this.timeout); }
Menu.prototype.menuTimer = function(){
this.closetimer = setTimeout(this.menuClose.bind(this), this.timeout);
}
您可以访问它时定义对菜单(this)的引用。
Menu.prototype.menuTimer = function(){
var _self = this;
this.closetimer = setTimeout(function(){
_self.menuClose();
}, this.timeout);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.