在 Javascript 构造函数中引用实例变量 [英] Reference Instance Variables in Javascript Constructor

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

问题描述

我正在尝试通过执行以下操作来维护对象的状态:

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

我想在调用 changeState 方法时将实例变量 foo 设置为bar".

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

例如:

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

据我所知,发生的事情是内部匿名函数中的this"指向窗口.我不确定发生了什么.

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?

推荐答案

除非您在调用函数时指定 this 上下文,否则默认将是全局的(在浏览器中是窗口).

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

替代方案是:-

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

};

或:-

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天全站免登陆