require()和module.exportsjavascript
使用當即執行函數的寫法,外部代碼沒法讀取內部的_count變量java
let module = (function() { let _count = 0 let m1 = function() { console.log(_count) } let m2 = function() { console.log(_count + 1) } return { m1: m1, m2: m2 } })
使用export導出,用於規定模塊的對外接口函數
一個模塊是一個獨立文件,文件內的全部變量或函數或類外部沒法獲取,若是但願獲取到,必須使用export關鍵字ui
(1) 輸出變量或者函數、類code
輸出變量繼承
// profile.js export let firstName = 'Mc' export let lastName = 'IU' export const year = 2017
另外一種寫法,優先考慮下面這種寫法接口
let firstName = 'Mc' let lastName = 'IU' const year = 2017 export {firstName, lastName, year}
輸出一個函數ip
function v1() { } function v2() { } export { v1 as namedV1, // as關鍵字重命名 v2 }
(2) export語句輸出的接口,與其對應的值是動態綁定關係,能夠取到模塊內部實時的值ci
export let foo = 'baz' setTimeout(() => foo = 'baz', 500) // 輸出foo值爲bar,500毫秒以後變爲baz
(3) export default命令,默認輸出element
// default.js // 匿名函數 export default function() { console.log('foo') } // 非匿名函數 export default function foo() { console.log('foo') } // 另外一種寫法 function foo() { console.log('foo') } export default foo
default後不能跟變量聲明語句
// 錯誤 // export default let a = 1 let a = 1 export default a
輸出類
export default class {} import Name from 'Myclass' let o = new Name()
(4) 須要注意的正確的寫法
// 錯誤寫法 // ①export 1 // ②let m = 1; export m // 變量的export正確寫法 export let m = 1 let m = 1 export {m} let n = 1 export {n as m} // 函數或類export正確寫法 export function f() {} function f() {} export {f}
使用import導入,用於獲取其餘模塊提供的功能
使用export命令定義了模塊的對外接口後,其餘JS文件就能夠經過import來加載這個模塊
(1) 引入變量
// main.js import {firstName, lastName, year} from './profile' function setName(element) { element.textContent = firstName + ' ' + lastName } // 一樣可重命名 import {lastName as listame} from './profile'
(2) import具備提高效果
foo() import {foo} from 'my_module' // 不會報錯,可正常調用foo函數
(3) 總體加載
// circle.js function area(radius) { return Math.PI * radius * radius } function circumference(radius) { return 2 * Math.PI * radius }
// main.js import {area, circumference} from './circle' // 逐個加載 area(4) circumference(14) import * as circle from './circle' // 總體加載 circle.area(4) circle.circumference(14)
(4) 引入默認導出
// 默認導出 export default function crc32() {} import anyName from 'crc32' // 非默認導出(注意大括號) export function crc32() {} import {crc32} from 'crc32'
模塊的繼承
假設有一個circleplus模塊,繼承了circle模塊:
// circleplus.js export * from 'circle' // 繼承了circle的全部屬性和方法 export let e = 2.718 export default function(x) { return Math.exp(x) }
上面代碼中的export ,表示再輸出circle模塊的全部屬性和方法。注意export 命令會忽略circle模塊的default方法。
而後,上面代碼又輸出了自定義的e變量和默認方法。
這時,也能夠將circle的屬性或方法,更名後再輸出:
// circleplus.js export {area as circleArea} from 'cricle'
上面代碼表示,只輸出circle模塊的area方法,且將其更名爲circleArea。
加載方法以下
// math.js import * as math from 'circleplus' import exp from 'circleplus' console.log(exp(math.e))