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 設計模式
程式碼重用模式
   
141
6-10 Firebug 檢驗 cake 物件
如果你原本就已經習慣混搭的概念,特別是將混搭作為正式的一部分的語言。你也許會預期
改變一個或多個父物件,也會影響到子物件,不過上述的實作不會這樣。在這裡我們只是巡
訪並複製屬性,並切斷了和父物件之間的連結。
借用方法
有的時候會發生這樣的情況:你只喜歡現有物件的其中一兩個方法,你想要重用它們,
但不希望對該物件建立父子物件關係。你只想要使用你所喜歡的方法,而不想繼承其
他所有你根本用不到的方法。藉由借用方法模式,這是可能的。此模式是受益於函式的
call()
apply()
方法。你其實已經在本書中看過這個模式了,甚至在本章之中,例如
extendDeep()
的實作中也用過。
如你所知,JavaScript 中的函式是物件,且它們自身也帶有些有趣的方法,例如
call()
apply()
。這兩者唯一不同之處在於,其中一個接受用陣列表示的參數,來傳遞給要呼
叫的方法,另一個則接受一個個獨立的參數
。你可以用這兩個方法來向現有的物件借用
功能:
這裡你有個物件稱為
myobj
,而且你知道有另一個
notmyobj
物件裡有個很有用的方法名
doStuff()
。我們不要經歷那些繼承的麻煩事,還繼承了一堆
myobj
根本就不需要的方
法,取而代之,你可以只是暫時地借用
doStuff()
方法。
你傳入你的物件和任意的參數,讓借來的方法將其自身的
this
綁定至你的物件。基本
上,為了得益於你想要的方法
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