簡體   English   中英

有和沒有新運算符的JavaScript構造函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM