是什麼在代碼的下面兩個區塊的工作不同。雙方似乎同樣的工作(我知道,第一是正確的,第二次是沒有,但不同的是什麼?)。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
http://stackoverflow.com/questions/32978852/is-javascript-new-keyword-optional-for-javascript-api-feature – tanenbring
第二個不創建實例。它將屬性添加到'window'對象。如果您嘗試運行在嚴格模式下的代碼,它會崩潰,因爲你會被分配屬性'undefined'。 –