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

前端 未结 3 788
轮回少年
轮回少年 2020-12-10 04:41

I have this class/function

function Menu()
{
  this.closetimer = 0;
  this.dropdown = 0;
}

Menu.prototype.menuTimer = function()
{
  this.closetimer = setTi         


        
相关标签:
3条回答
  • 2020-12-10 04:57

    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);
    }
    
    0 讨论(0)
  • 2020-12-10 05:14

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

    Menu.prototype.menuTimer = function(){
        var self = this;
        this.closetimer = setTimeout(function(){
            self.menuClose();
        }, this.timeout);
    }
    
    0 讨论(0)
  • 2020-12-10 05:18

    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(this.menuClose.bind(this), this.timeout);
    }
    
    0 讨论(0)
提交回复
热议问题