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 設計模式
實字與建構式
   
47
強制 new 的模式
先前曾提過,建構式只是使用
new
呼叫而已,但本質上還是函式。那萬一你忘了加上
new
會發生什麼事呢?這不會造成任何語法或執行期的錯誤,但會導致邏輯的錯誤和非預期的
行為。因為當你忘了
new
,建構式中的
this
會指向全域物件,例如在瀏覽器環境中會指
window
若你的建構式中有類似
this.member
的程式碼,且你呼叫建構式時忘了加上
new
,你其實
是在為全域物件增加新的屬性,存取起來就類似
window.member
或只是
member
。這樣的
行為極不可取,因為你也知道你應該盡力讓全域作用域保持乾淨。
[44]
這種討人厭的行為有在 ECMAScript 5 中解決,而且在嚴格模式中
this
不會再指向全域
物件。如果不能使用 ES5,還是有辦法可以保證建構式函式即使不使用
new
也能有正確的
行為。
命名慣例
使
MyConstructor
)、讓「一般」函式和方法首字母小寫(
myFunction
)。
使用 that
遵循命名慣例肯定有幫助,但它僅僅只是建議而不能強制採用正確的行為。接下來這個模
式可以幫你保證你的建構式運作起來就是個建構式:不將成員加至
this
,取而代之加入
that
並且回傳
that
建構式
一個新物件
反模式:
忘了「new
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