2016-01-21 32 views
0

是什麼在代碼的下面兩個區塊的工作不同。雙方似乎同樣的工作(我知道,第一是正確的,第二次是沒有,但不同的是什麼?)。JavaScript的構造有和沒有新的運營商

function Album(title, artist) { 
    this.title = title; 
    this.artist = artist; 
    this.play = function() { 
     console.log("Playing " + this.title + " - " + this.artist); 
    }; 
} 
var darkside = new Album("Dark Side of the Cheese", "Pink Mouse"); 
darkside.play(); 

而同樣的代碼,但是構造與return this並沒有new操作

function Album(title, artist) { 
    this.title = title; 
    this.artist = artist; 
    this.play = function() { 
     console.log("Playing " + this.title + " - " + this.artist); 
    }; 
    return this; 
} 
var darkside = Album("Dark Side of the Cheese", "Pink Mouse"); 
darkside.play(); 

都返回相同的結果創建對象的實例:

Playing Dark Side of the Cheese - Pink Mouse 
+0

http://stackoverflow.com/questions/32978852/is-javascript-new-keyword-optional-for-javascript-api-feature – tanenbring

+0

第二個不創建實例。它將屬性添加到'window'對象。如果您嘗試運行在嚴格模式下的代碼,它會崩潰,因爲你會被分配屬性'undefined'。 –

回答

2

這個 「作品」,因爲this而不new解析爲window在瀏覽器中的上下文,因此設置titlewindow對象到title參數的屬性。

您應該使用new所以它在正確的上下文關係和正確地創建自己的屬性的新對象。

function Album() { alert(this==window); }; x = Album(); // true 
function Album() { alert(this==window); }; x = new Album(); // false 

所以,如果你做另一個實例,this.title將覆蓋以前的等等,你不會有任何獨立的對象存儲title用。

+0

我在Node中運行所有,而不是在瀏覽器中運行。如果我們用'global'交換'window',那麼同樣的邏輯工作呢? – Alexander

+0

@亞歷山大是的,同樣的事情。 – Paulpro