[英]Are there problems with calling JavaScript constructors as functions(without new?)
[英]JavaScript constructors with and without new operator
以下兩個代碼塊的工作區別是什么? 兩者似乎工作類似(我知道第一個是正確的,第二個不是正確的,但是有什么區別呢?)。
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
之所以“有效”,是因為this
沒有new
可以在瀏覽器上下文中解析為window
,因此將window
對象的title
屬性設置為title
參數。
您應該使用new
以便在正確的上下文中構造它,並正確創建一個具有自己屬性的新對象。
function Album() { alert(this==window); }; x = Album(); // true
function Album() { alert(this==window); }; x = new Album(); // false
因此,如果您創建了另一個實例,則this.title
將覆蓋先前的實例,依此類推,並且您將沒有任何獨立的對象來存儲title
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.