Reference instance variables in Javascript constructor

I am trying to save the state of 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 example:

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 internal anonymous function points to the window. I'm not sure what's going on.

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

+2


source to share


4 answers


If you do not specify this context when calling the function, then by default it will be global (in browsers this is a window).

Alternatives: -

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.
  }; 

      

};



+2


source


this topic appears a lot, but is difficult to download as "this" is being removed from SO queries.

Basically, JavaScript this

always refers to the caller, not the context object. Since here we are calling o.changeState () from the global scope, this

refers to the window.



You really don't need an internal close function to work in this case - the function itself is changeState

enough to close the lexical scope.

obj = function()
{
  var self = this; 
  this.foo = undefined; 
  this.changeState = function()
  {
    self.foo = "bar";
  }
} 

      

+3


source


function obj() { 
    this.foo = undefined; 
    this.changeState = function () { this.foo = "bar" };
};

var o = new obj();
o.changeState();
alert(o.foo);

      

works for me. I'm not sure why you would want to use a self-triggering function just to assign a function reference, and also why you are using a function expression for your constructor rather than a function declaration.

+2


source


I understood that. You just need to save a link to the current context and use it in an internal anonymous function:

obj = function() { 
    this.foo = undefined; 
    var self = this; 
    this.changeState = function () { 
        (function () { self.foo = "bar" })();
    }; 
}; 

      

+1


source







All Articles