【问题标题】:Javascript - Object StateJavascript - 对象状态
【发布时间】:2013-10-19 12:19:25
【问题描述】:

我可能不正确地处理这个......

我正在尝试在内部跟踪对象状态并使用它来调用修改后的方法:

createObject = function() {
  this.a = 1

  this.method1 = function() {
  if (this.a == 1 ) {
    //do stuff
    this.a = 0
  }
}

var x = new createObject()

不幸的是,内部没有跟踪状态。但是,如果我更改另一个对象的属性,它会完美运行:

otherObj = { a:1 }

createObject = function() {

  this.method1 = function() {
  if (this.a == 1 ) {
    //do stuff
    otherObject.a = 0
  }

}

var x = new createObject()

这是处理这个问题的正确方法吗?

【问题讨论】:

  • “很遗憾,没有在内部跟踪状态。”到底出了什么问题?
  • @Sniffer - 由于 this.a 未更新,我的方法无法正常运行

标签: javascript javascript-objects


【解决方案1】:

你有问题,因为method1() 中的this 与外部函数中的this 不同。那是因为在 JS 函数中创建了作用域。

第一种方法

所以你可能希望a 是一个变量,而不是this 的属性:

createObject = function() {
  // 'a' is now available here...
  var a = 1

  this.method1 = function() {
    // ... and here as well.
    if (a == 1 ) {
      a = 0
    }
  }
}

第二种方法

或者,您可能希望在辅助变量(在本例中称为 self)中保存对外部 this 的引用:

createObject = function() {
  // 'self' is a regular varialbe, referencing 'this'
  var self = this;
  this.a = 1

  this.method1 = function() {
    // Here, self !== this, because 'this' in method1() 
    // is different from 'this' in outer function.
    // So we can access 'self.a':
    if (self.a == 1 ) {
      //do stuff
      self.a = 0
    }
  }
}

第三种方法

最后,您还可以使用bind() 将外部this 绑定到您的method1()

var createObject = function () {
    this.a = 1

    this.method1 = function () {
        console.log(this.a);
        if (this.a == 1) {
            this.a = 0
        }
    }.bind(this);
    // ^ note `bind(this)` above. Now, 'this' inside 'method1'
    // is same as 'this' in outer function.
}

Here is a docbind()。请注意,它在 IE

【讨论】:

  • 很好解释的答案
  • 当您将method1 作为createObject 的方法调用时,method1 内部的this.a 不会引用this 构造函数内部this 引用的相同a ?
  • @Sniffer - 如果你这样称呼它,是的,它应该。我跳过了那部分,因为 OP 没有具体说明他如何称呼method1() - 查看症状我认为他有this-问题。
  • @JamieStrauss - 是的,拥有var that = this; 是一种常见的做法(它的调用方式多种多样,常见的有:thatself_this)。如果您想真正了解它们,我不能推荐任何比Dimtry Soshnikov's blog series 更高级的东西 - 这是一篇长篇文章,但在解释范围和其他 JS 特性方面做得非常出色。当然比阅读 ECMAScript 标准本身更好;)
  • 我在大约 2.5 年后(在投票后)回到这个问题,这仍然是那些让我“啊哈!”的答案之一。时刻。
猜你喜欢
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多