Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 closetimer object.

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

like image 492
polyhedron Avatar asked Nov 01 '10 20:11

polyhedron


3 Answers

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);
}
like image 111
Nick Craver Avatar answered Nov 12 '22 22:11

Nick Craver


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);
}
like image 7
clockworkgeek Avatar answered Nov 13 '22 00:11

clockworkgeek


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);
}
like image 4
Gabriele Petrioli Avatar answered Nov 12 '22 23:11

Gabriele Petrioli