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.ainsidemethod1
引用了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.
}