2013-10-19 46 views
4

我可能是這個錯誤地接近......使用Javascript - 對象狀態

我試圖跟蹤對象的內部狀態,並用它來調用修改方法:

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

這是解決這個正確的方法是什麼?

+2

「不幸的是,狀態不在內部跟蹤。」究竟發生了什麼問題? –

+0

@Sniffer - 由於_this.a_沒有被更新,我的方法運行不正確 –

回答

12

您有問題,因爲thismethod1()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 
    } 
    } 
} 

第二條本辦法

或者,你可能要舉行在輔助變量中稱爲this(稱爲在10這個例子):

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 < 9.

+0

很好地解釋了答案 – Ghost

+0

當你調用'method1'作爲'createObject'的方法時,''this.a'裏面' method1'指的是'createObject'構造函數內的'this'引用的相同'a'? –

+0

@Sniffer - 如果你這樣稱呼它,是的,它應該。我跳過那部分,因爲OP沒有指定他如何調用'method1()' - 看着我認爲他有'this'問題的症狀。 – kamituel