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))