Jam*_*uss 4 javascript javascript-objects
我可能正在接近这个......
我试图在内部跟踪对象状态并使用它来调用修改后的方法:
createObject = function() {
this.a = 1
this.method1 = function() {
if (this.a == 1 ) {
//do stuff
this.a = 0
}
}
var x = new createObject()
Run Code Online (Sandbox Code Playgroud)
不幸的是,州没有被内部跟踪.如果我改变另一个对象的属性,它可以完美地工作:
otherObj = { a:1 }
createObject = function() {
this.method1 = function() {
if (this.a == 1 ) {
//do stuff
otherObject.a = 0
}
}
var x = new createObject()
Run Code Online (Sandbox Code Playgroud)
这是接近这个的正确方法吗?
kam*_*uel 13
你有问题,因为this在method1()从不同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
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二种方法
或者,您可能希望this在辅助变量(self在此示例中调用)中保留对外部的引用:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
第三种方法
最后,您还可以使用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.
}
Run Code Online (Sandbox Code Playgroud)
这里是一个文档的bind().请注意,它在IE <9中不可用.