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 設計模式
138
   
第六章
你也許也在某些 JavaScript 函式庫中可以找到原型繼承模式的實作;例如 YUI3
Y.Object()
方法:
用複製屬性實作繼承
我們來看看另一個繼承模式—用複製屬性來繼承。在這個模式中,物件向其他物件取得功
能的方式,只是簡單的使用複製。下面是用來複製屬性的範例函式
extend()
的實作:
這是個簡單的實作,只是用迴圈尋訪父物件的每個成員並複製它們。在這份實作中
child
是選用的,意思是若你沒有傳遞現成的物件來擴充,那麼會建立一個全新的物件並回傳:
這裡所做的,就是所謂對物件的「淺層複製」(shallow copy)。而「深層複製」指的
是:會檢查你所要複製屬性的是否為物件或陣列,若是的話,會用遞迴的方式進入該物
件,一樣尋訪每個屬性並複製。使用淺複製的時候,因為 JavaScript 的物件是使用參考來
傳遞,如果你改變了子物件的屬性值,只要該屬性是物件,那麼你也同時改變了父物件的
屬性。這樣的特性較適合方法(因為函式也是物件、也是用參考傳遞),但對於物件和陣
列,則會讓人感到意外。考慮這個例子:[133]
ECMA5 表示符
程式碼重用模式
   
139
現在讓我們修改
extend()
函式,來做一個深層複製的版本。你需要做的就是檢查屬性是
否為物 ...
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