Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Instance Variables in Javascript Constructor

I'm trying to maintain state on an object by doing something like this:

obj = function() { 
    this.foo = undefined; 
    this.changeState = function () { 
        (function () { this.foo = "bar" })(); // This is contrived, but same idea.
    }; 
};

I want to set the instance variable foo to "bar" when I call the changeState method.

For instance:

o = new obj();
o.changeState();
alert(o.foo); // This should say "bar"

As far as I can tell, what is happening is that "this" in the inner anonymous function is pointing to window. I'm not sure what's going on.

Am I on the right track? Is there a better approach?

like image 839
gaustin Avatar asked Dec 17 '22 06:12

gaustin


2 Answers

this topic comes up a lot, but it's hard to serach for since "this" is removed from SO searches.

Basically, in JavaScript, this always refers to the calling object, not the context object. Since here we call o.changeState() from the global scope, this refers to window.

You actually don't need the inner function for the closure to work in this case - the changeState function itself is enough to close a lexical scope.

obj = function()
{
  var self = this; 
  this.foo = undefined; 
  this.changeState = function()
  {
    self.foo = "bar";
  }
} 
like image 196
Peter Bailey Avatar answered Dec 28 '22 00:12

Peter Bailey


Unless you specify a this context when calling a function the default will be the global (which in browsers is window).

Alternatives are:-

obj = function() { 
  this.foo = undefined; 
  this.changeState = function () { 
    (function () { this.foo = "bar" }).call(this); // This is contrived, but same idea.
  }; 

};

or:-

obj = function() {
  var self = this;
  this.foo = undefined; 
  this.changeState = function () { 
    (function () { self.foo = "bar" })(); // This is contrived, but same idea.
  }; 

};

like image 44
AnthonyWJones Avatar answered Dec 27 '22 22:12

AnthonyWJones