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 設計模式
152
   
第七章
關於 factory 模式的實作沒有什麼特別困難的部分。你需要做的,就只是根據要求的類
型,找到建立物件的建構式。在這個案例中採用了一個簡單的命名慣例,用來將物件類
型對應至建構式。繼承的部分,則只是一種「可將常見的重複程式碼抽成方法」的一個
例子。在這裡我們將重複的程式片段放進 factory 方法,而不是讓它們在每個建構式中都
出現。
內建的物件 Factory
而為了舉一個「真實世界中的工廠」的例子,我們來考慮內建的全域
Object()
建構式。
它的行為也是 factory,因為它會根據輸入產出不同的物件。若你傳進去的是原始數值,它
可以在幕後用
Number()
建立物件,對於字串和布林也是一樣。而對於其他的類型的值,
包括無輸入的情況,它會建立普通的物件。
靜態的 factory 方法
若建構式不存在則拋出錯誤
到這裡時我們已經知道建構式存在了
我們讓它繼承父建構式,但僅此一次
建立新實體
選擇性的呼叫一些方法,然後回傳
定義具體的 car maker
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