2012-02-21 85 views
4

我在這裏讀了一篇文章:JavaScript對象創造模式

http://javascriptweblog.wordpress.com/2010/03/16/five-ways-to-create-objects/

它講述了約五創建對象的方式。但我的問題是他的方式一(3):

myApp.Notepad = function(defaultFont) { 
    var that = {}; 
    that.writeable = true; 
    that.font = defaultFont; 
    that.setFont = function(theFont) { 
     that.font = theFont; 
    } 
    return that; 
} 

myApp.notepad1 = myApp.Notepad('helvetica'); 

按作者,我們可以使用它時,多個實例需要,我們可以使用從3(以上)的任何圖案以5

但據我所知,我們確實需要使用this關鍵字,它反映了新創建的實例,並且僅指那個實例。但是,以上,作者使用that對象而不是this,並且上面沒有使用new關鍵字。它將如何應用於多個對象實例?它是否與使用this相同?

回答

4

在您的例子,that是通過這條線創建新對象:

var that = {}; 

該函數然後前進到設置該對象的屬性。

在另一方面,this使用具有構造函數 - 使用new調用時,將自動創建一個新對象,並傳遞給函數作爲this。同樣的例子可以寫成:

的使用對象字面構造器(代碼)的
myApp.Notepad = function(defaultFont) { 
    this.writeable = true; 
    this.font = defaultFont; 
    this.setFont = function(theFont) { 
     this.font = theFont; 
    } 
} 

myApp.notepad1 = new myApp.Notepad('helvetica'); 
+0

感謝,但我知道什麼是優勢,使用'that'對象,而不是使用'this'構造方法的? – Dev555 2012-02-21 05:49:36

+1

@ Dev555 - 這只是一種不同的(圍繞)「構建」對象的方式。我不知道它是否有優勢,但微妙之處在於'setFont'函數使用閉包,而不是引用'this'對象。 'setFont'使用在其外部定義的那個''''。從語法上講,它稍微不清楚它在做什麼,因爲它會對'new'運算符進行旁路操作。 – Seth 2012-02-21 06:05:00

+0

@Seth:這就是混亂,等待事情得到澄清。謝謝 – Dev555 2012-02-21 06:10:35

2

一個優勢還沒有被指出,但是,當你創建了一個對象的新實例,該new關鍵字不是必需的。或者換句話說,如果你只是忘記使用new關鍵字,您的代碼將仍然運行如預期,你不再是依賴於使用的new關鍵字中以得到this範圍,新創建的對象的構造函數; that對象現在正在考慮你的範圍。

這是YUI庫(和Douglas Crockford)爲構造函數所採用的方法。

考慮以下的簡單構造函數:

var Car = function(model){ 
    this.model = model; 
}; 

如果你打電話給Car('Dodge Viper');甚至var MyCar = Car('Dodge Viper');,則this在功能實際上指的是全球window對象。所以現在上面的屬性Model實際上是一個全局變量,這可能不是預期的。

var Car = function(model) { 
 
    var that = {}; 
 
    that.model = model; 
 
    return that; 
 
}; 
 

 
// Both work the same. 
 
var MamsCar = new Car("Mini Cooper"); // with 'new' 
 
var DadsCar = Car("Bugatti Veyron"); // without 'new' 
 
alert("Mam's car is a " + MamsCar.model + " and dad's car is a " + DadsCar.model);