Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.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 如何访问原型&x27;从一个方法';s函数_Javascript_Prototype - Fatal编程技术网

Javascript 如何访问原型&x27;从一个方法';s函数

Javascript 如何访问原型&x27;从一个方法';s函数,javascript,prototype,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(

我有这个类/功能

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()

如何从
menuTimer()
中的菜单对象引用
menuClose()

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

您可以在访问菜单时定义对该菜单的引用

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

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


您应该使用
var\u self
来防止与全局名称空间的冲突。这可以写为
setTimeout(this.menuClose.bind(this),this.timeout)
?您完全正确,我已经更新了它来显示。这是迄今为止最好的解决办法。给我所有的选票!这听起来确实有点贪婪:-)与jQuery中prototype的bind函数等价的是$.proxy。非常有用。他们说jQuery写起来更短!:-P
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);
}