Skip to Main Content
現代JavaScript實務應用
book

現代JavaScript實務應用

by Nicolas Bevacqua
May 2018
Intermediate to advanced content levelIntermediate to advanced
336 pages
5h 16m
Chinese
GoTop Information, Inc.
Content preview from 現代JavaScript實務應用
260
|
第八章 JavaScript 模組
8.1 CommonJS
不像其他的模組樣式需要程式化地宣告,在 CommonJS 中,每個檔案都
是一個模組。當
global
全域作用域需要被明確地存取時,CommonJS
個模組有內定的本地作用域。CommonJS 模組可以動態地匯出一個公開
的介面,與使用者進行互動;CommonJS 也可以動態地匯入模組的相依
性,透過
require
函式呼叫解決相依性問題。這些
require
函式呼叫是
同步的,並回傳使用介面給需要的模組。
說明這些模組定義而沒有看看一些程式範例,可能不容易理解。下面的
程式碼展示一個可重複使用的 CommonJS 模組檔案。
has
union
函式
均為本地作用域,僅能在模組中使用;若我們將
union
指派給
module.
exports
,就可以將我們的模組變成公開的 API
function has(list, item) {
return list.includes(item)
}
function union(list, item) {
if (has(list, item)) {
return list
}
return [...list, item]
}
module.exports = union
若取用上述的程式片段儲存為
union.js
,這樣就可以在其他的 CommonJS
模組中使用
union.js
了。我們先稱這個模組為
app.js
。為了使用
union.js
我們會呼叫
require
並提供它
union.js
的檔案路徑。
const ...
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.
Start your free trial

You might also like

精實企業|高績效組織如何達成創新規模化

精實企業|高績效組織如何達成創新規模化

Jez Humble, Joanne Molesky, Barry O'Reilly
C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
優雅的SciPy|Python科學研究的美學

優雅的SciPy|Python科學研究的美學

Juan Nunez-Iglesias, Stéfan van der Walt, Harriet Dashnow

Publisher Resources

ISBN: 9789864767885