JavaScript构造函数中的参考实例变量 [英] Reference Instance Variables in Javascript Constructor

查看:97
本文介绍了JavaScript构造函数中的参考实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过做这样的事情来保持对象的状态:

  obj = function b $ b this.foo = undefined; 
this.changeState = function(){
(function(){this.foo =bar})(); //这是设计的,但是同样的想法。
};
};



当我调用changeState方法时,我想将实例变量foo设置为bar p>

例如:

  o = new obj 
o.changeState();
alert(o.foo); //这应该说bar

据我所知,这个在内部匿名函数指向窗口。我不知道发生了什么。



我在正确的轨道上吗?有没有更好的方法?

解决方案

除非你在调用函数时指定这个上下文,默认将是全局

  obj = 

function(){
this.foo = undefined;
this.changeState = function(){
(function(){this.foo =bar})。 //这是设计的,但是同样的想法。
};

};



/ p>

  obj = function(){
var self = this;
this.foo = undefined;
this.changeState = function(){
(function(){self.foo =bar})(); //这是设计的,但是同样的想法。
};

};


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?

解决方案

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

};

这篇关于JavaScript构造函数中的参考实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆