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

时间:2010-11-01 20:25:25

标签: javascript prototype

我有这个类/功能

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');
}

我想调用属于Menu类的函数menuClose(),但我认为此代码实际上是尝试从menuClose()对象调用closetimer

如何从menuClose()

中的菜单对象中引用menuTimer()

3 个答案:

答案 0 :(得分:16)

setTimeout()回调中,this引用window,只需保留这样的引用:

Menu.prototype.menuTimer = function(){
    var self = this;
    this.closetimer = setTimeout(function(){
        self.menuClose();
    }, this.timeout);
}

答案 1 :(得分:6)

另一种方法是绑定内部函数。

<击>

<击>
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);
}

答案 2 :(得分:4)

您可以在访问菜单时定义对菜单(this)的引用..

Menu.prototype.menuTimer = function(){
    var _self = this;
    this.closetimer = setTimeout(function(){
        _self.menuClose();
    }, this.timeout);
}