2016-12-30 18 views
0

這是我修改的基於one by Rob Dodson的示例。具有緩存靜態屬性的JavaScript單例模式如何工作?

function User() { 
    // do we have an existing instance? 
    if (User.instance) { 
     return User.instance; 
    } 

    // proceed as normal 
    this.firstName = 'John'; 
    this.lastName = 'Doe'; 

    // cache 
    User.instance = this; 

    // implicit return 
    // return this; 
} 

a = new User(); 
b = new User(); 
b.firstName = "Paul" 
console.log(a) 

我剛學,所以我可能會使用打下術語,但如果我理解正確,User.instance = this;克隆User,而克隆成爲唯一User我們可以訪問了。因此,全過程中它經過是這樣的:

a = new User();

做我們現有的User.instance?所以繼續通過代碼並將a.firstName設置爲John,將a.lastName設置爲Doe。現在製作一個名爲John Doe的this對象的副本,並將其設置爲User構造函數的永久部分。是什麼使它永久?因爲代碼永遠不會再次設置該行。爲什麼?因爲...

b = new User();

我們有現成的User.instance?是。所以returnUser.instance我們已經存儲,並退出功能。

a是指User.instance - 我不明白this的隱性回報是如何返回到a - 而b是它的克隆。

+0

函數也可以有屬性,所以設置'User.instance = this;'將函數本身第一次創建的內存保存起來。所以當它再次被調用時,它會檢測它的實例屬性是否存在,並返回緩存的實例。而b不是一個克隆,它是對同一個對象的引用,因此當你將b.firstName改爲paul時,a.firstName也是paul。 – Shilly

回答

1

,如果我理解正確的話,User.instance = this;克隆用戶,並克隆成爲...
......使這個對象的副本...

號分配不復制/克隆的對象,它的分配從右側到左側的變量(或屬性等)非常相同的對象引用。這就是爲什麼a === User.instanceb = User.instance

b = new User(); - new User()的返回值沒有被克隆或什麼,但直接分配給b

+0

'a = new User();'?爲什麼第一次運行時返回值不會被定義? – stephen

+0

由於使用'new'調用的構造函數隱式返回實例 - 因爲代碼中的註釋提及 – Bergi

相關問題