Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-对象状态_Javascript_Javascript Objects - Fatal编程技术网

Javascript-对象状态

Javascript-对象状态,javascript,javascript-objects,Javascript,Javascript Objects,我可能处理得不对 我试图在内部跟踪对象状态,并使用它调用修改过的方法: createObject = function() { this.a = 1 this.method1 = function() { if (this.a == 1 ) { //do stuff this.a = 0 } } var x = new createObject() 不幸的是,国家没有被内部跟踪。但是,如果我更改另一个对象的属性,它将完美工作: otherObj = { a:

我可能处理得不对

我试图在内部跟踪对象状态,并使用它调用修改过的方法:

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()

这是正确的方法吗?

您遇到了问题,因为
method1()
中的
与外部函数中的
不同。这是因为在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
的引用:

第三种方法

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


对于
bind()
。请注意,它在IE<9中不可用。

“不幸的是,状态没有被内部跟踪。”到底出了什么问题?@Sniffer-因此,我的方法没有正确运行。当您将
方法1
作为
createObject
的方法调用时,未被更新的问题得到了很好的解释,不
this.a
inside
method1
引用了
this
createObject
构造函数中引用的同一
a
。@Sniffer-如果你这样称呼它,是的,它应该这样。我跳过了这一部分,因为OP没有指定如何调用
method1()
-查看症状,我假设他有
这个问题。@JamieStrauss-是的,通常的做法是使用
var=this
(它的调用方式多种多样,常见的有:
that
self
\u this
)。如果你想真正理解它们,我不能推荐任何比这更高的东西——这是一本很长的书,但在解释作用域和其他JS特性方面做得非常出色。当然比阅读ECMAScript标准本身要好;)2.5年后(经过一次投票后),我又回到这个问题上,这仍然是给我一个“啊哈!”时刻的答案之一。
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
    }
  }
}
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.
}