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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4072770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:19:21  来源:igfitidea点击:

How to access a prototype's parent this from within a method's function

javascriptprototype

提问by polyhedron

I have this class/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');
}

I want to call the function menuClose()which is part of the Menu class, but I think this code actually tries to call menuClose()from the closetimerobject.

我想调用menuClose()属于 Menu 类的函数,但我认为这段代码实际上试图menuClose()closetimer对象调用。

How do I reference menuClose()from the Menu object from within menuTimer()?

如何menuClose()从内部引用Menu 对象menuTimer()

回答by Nick Craver

In your setTimeout()callback, thisrefers to window, just keep a reference like this:

在您的setTimeout()回调中,this引用window,只需保留如下引用:

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

回答by clockworkgeek

Another way is to bind the inner function.

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

Menu.prototype.menuTimer = function(){
 this.closetimer = setTimeout(function(){
  this.menuClose();
 }.bind(this), 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);
}

回答by Gabriele Petrioli

you define a reference to the Menu (this) while you have access to it..

您可以在有权访问它的同时定义对菜单(此)的引用。

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