Skip to Content
JavaScript 設計模式
book

JavaScript 設計模式

by Stoyan Stefanov
March 2012
Intermediate to advanced
244 pages
4h 42m
Chinese
GoTop Information, Inc.
Content preview from JavaScript 設計模式
148
   
第七章
儲存在 Closure 中的實體
另一種作法是使用 closure 來保護那份唯一實體。你可以藉由第五章討論的 private 靜態成
員模式來實作。這裡的秘訣是重新定義建構式:
原本的建構式在第一次會被呼叫,而它也如常回傳
this
。接著第二次以後,執行的都是
重新定義的建構式。新的建構式會透過 closure 取得 private
instance
並回傳。
這份實作其實也是第四章裡面自我定義函式模式的一個例子。其缺點是,就如在第四章討
論過的,重新定義後的函式(在本例中是
Universe()
建構式)會失去在初次定義到重新
定義之間加在它身上的屬性。在我們現在具體的情況,你加在
Universe()
原型的屬性不
會及時連結(live link)到稍早用原本實作建立的實體。
以下的測試可以讓你看出問題:
[144
]
測試看看:
快取的實體
用一般的方式繼續
重新定義建構式
試試看
新增屬性至原型
再次新增屬性至原型
只有一開始的原型有連接到物件上
在建立初始物件之後
設計模式
   
149
之所以
uni.constructor
不再和
Universe()
建構式相等,是因為
uni.constructor
仍指
向著原本的建構式,而不是重新定義後的那一個。
若因為需求,要讓原型和建構式指
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript 之美

JavaScript 之美

Anton Kovalyov
重構 JavaScript

重構 JavaScript

Evan Burchard

Publisher Resources

ISBN: 9789862764190