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 設計模式
物件建立模式
   
115
鏈接模式的優點與缺點
使用鏈接模式的一個優點是你可以少打一些字,且產生較精簡的程式碼,讀起來甚至像普
通的句子一般。
另一個優點,是幫助你去思考能不能切割你的函式,建立更小、更專門的函式,而不是做
了太多工作的函式。長遠來說,這樣可以提升可維護性。
而缺點是這種寫法會讓 dubug 時變得困難。你可能已經知道錯誤是發生在某一行,但那行
實在發生了太多事情,所以當鏈接著的其中一個方法無聲無息的出錯了,你根本不知道是
哪一個方法。Robert MartinClean Code 的作者,甚至稱此為「火車事故」模式。
不管怎樣,認識這個模式是很好的,而當你建立的方法,沒有明顯有意義的回傳值時,
你可以回傳
this
。這個模式被廣泛的使用,例如在 jQuery 函式庫中。而如果你仔細看看
DOM API,你可以注意到它們也是易於使用鏈接的結構,例如:
[111]
method() 方法
對於習慣用 class 思考的程式員,JavaScript 可能會讓他們感到困惑。這就是為什麼有些程
式員會選擇試圖將 JavaScript 編寫得更 class-likeDouglas Crockford 所提出的
method()
方法,其概念就是其中一種嘗試。 回想起來,其實他承認讓 JavaScript 變得 class-like
不是一種推薦的方式,但儘管如此,這還是一種很有趣的模式,你可能會在某些應用中碰
到。
使用建構式看起來就像在 Java 中使用 class,也讓你可以 ...
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