繁体   English   中英

如何从方法的函数中访问原型的父级

[英]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.

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