Skip to Content
JAVASCRIPT網頁應用程式設計
book

JAVASCRIPT網頁應用程式設計

by Alex MacCaw
January 2013
Intermediate to advanced
332 pages
5h 23m
Chinese
GoTop Information, Inc.
Content preview from JAVASCRIPT網頁應用程式設計
60
|
第四章
要在控制器裡定義任何全域變數,好讓控制器成為低耦合的程式元件。如果想做到上述
幾點,最佳方式莫過於採用接下來馬上要介紹的模組模式(module pattern)。
模組模式(Module Pattern
模組模式,是一種用來封裝程式邏輯、避免全域命名空間受到干擾的絕佳做法。要實現
這個模式,全得靠匿名函式(anonymous function)。匿名函式可以說是 JavaScript 中最
棒的功能。模組模式的做法,是先建立一組匿名函式,然後馬上執行它。這麼一來,就
可以確保匿名函式裡面所有的程式碼都被安全的隔離開來,為應用程式的變數,提供一
個隱閉、私密的空間:
(function(){
/* ... */
})();
在執行匿名函式之前,需要先用括號「
()
」把它包起來,否則 JavaScript 會沒辦法正確
解譯這段敘述句。
匯入全域變數(Global Import
在模組裡定義的變數全都是區域變數,在全域命名空間裡不能存取這些區域變數。但在
模組裡能隨心所欲的存取全域變數。不過要小心,在模組裡濫用全域變數,容易讓人搞
不清楚究竟有哪些全域變數被模組使用,而且隨著模組規模日益擴大,這個問題也會隨
之益發嚴重。
此外,JavaScript 解譯器也會需要花費較長的時間解譯這些藏身於模組裡的全域變數。
因為 JavaScript 解譯器需要循著作用域鏈(scope chain)一層一層往外找。相較之下,
存取區域變數的效能會比較好。
有種開發模組的做法,能輕易的幫我們解決上述問題。只要把全域變數當做參數傳進匿 ...
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 第3版 ―ES2015以降の最新ウェブ開発

初めてのJavaScript 第3版 ―ES2015以降の最新ウェブ開発

Ethan Brown, 武舎 広幸, 武舎 るみ
PHP编程:第4版

PHP编程:第4版

Kevin Tatroe, Peter MacIntyre
Strange Code

Strange Code

Ronald T. Kneusel
Perfecting Your Thinking Skills

Perfecting Your Thinking Skills

MIT Sloan Management Review

Publisher Resources

ISBN: 9789862766811