Reference Instance Variables in Javascript Constructor

我的未来我决定 提交于 2019-12-06 00:50:37

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

};

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";
  }
} 
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-invoking function just to assign a function reference, nor why you use a function expression for your constructor rather than a function declaration.

I figured it out. Just needed to save a reference to the current context and use that in the inner anonymous function:

obj = function() { 
    this.foo = undefined; 
    var self = this; 
    this.changeState = function () { 
        (function () { self.foo = "bar" })();
    }; 
}; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!