2009-09-08 129 views
2

我試圖做這樣的事情的對象上保持狀態:在JavaScript構造參考實例變量

obj = function() { 
    this.foo = undefined; 
    this.changeState = function() { 
     (function() { this.foo = "bar" })(); // This is contrived, but same idea. 
    }; 
}; 

我想設置的實例變量foo的爲「欄」當我打電話的改變狀態的方法。

例如:

o = new obj(); 
o.changeState(); 
alert(o.foo); // This should say "bar" 

據我所知道的,正在發生的事情是,「這個」在內部匿名函數指向窗口。我不確定發生了什麼事。

我在正確的軌道上嗎?有更好的方法嗎?

回答

2

:只需要保存當前上下文的參照和使用,在內部匿名函數。

替代是: -

obj = function() { 
    this.foo = undefined; 
    this.changeState = function() { 
    (function() { this.foo = "bar" }).call(this); // This is contrived, but same idea. 
    }; 

};

或: -

obj = function() { 
    var self = this; 
    this.foo = undefined; 
    this.changeState = function() { 
    (function() { self.foo = "bar" })(); // This is contrived, but same idea. 
    }; 

};

1

我想通了。除非你調用函數的默認將是全球(在瀏覽器裏面是窗口)時指定此背景下

obj = function() { 
    this.foo = undefined; 
    var self = this; 
    this.changeState = function() { 
     (function() { self.foo = "bar" })(); 
    }; 
}; 
2
function obj() { 
    this.foo = undefined; 
    this.changeState = function() { this.foo = "bar" }; 
}; 

var o = new obj(); 
o.changeState(); 
alert(o.foo); 

適合我。我不確定爲什麼要使用自調用函數來分配函數引用,也不知道爲什麼要爲構造函數而不是函數聲明使用函數表達式。

3

這個話題出現了很多,但很難搜索,因爲從SO搜索中刪除了「this」。

基本上,在JavaScript中,this總是指調用對象,而不是上下文對象。因爲這裏我們從全局範圍調用o.changeState(),所以this指向窗口。

實際上,在這種情況下,實際上並不需要閉包的內部函數 - changeState函數本身足以關閉詞法範圍。

obj = function() 
{ 
    var self = this; 
    this.foo = undefined; 
    this.changeState = function() 
    { 
    self.foo = "bar"; 
    } 
}