ECMAScript 6(ES6) 特性概览和与ES5的比较10-模块化

十.模块化

    • 1.输入/输出值
    • 2.默认值和通配符(wildcard 野卡片=通配符O(∩_∩)O)

1.输入/输出值

支持从模块导出或者导入值,而不会导致全局命名空间污染。

ECMAScript 6

// lib/math.js
export function sum (x, y) { return x + y }
export var pi = 3.141593

// someApp.js
import * as math from "lib/math"
console.log("2π=" + math.sum(math.pi, math.pi))

// otherApp.js
import {sum, pi} from "lib/math"
console.log(("2π=" + sum(pi, pi))

ECMAScript 5

// lib/math.js
LibMath = {};
LibMath.sum = function (x, y) {return x+y};
LibMath.pi = 3.141593;

// someApp.js
var math = LibMath
console.log("2π=" + math.sum(math.pi, math.pi));

// otherApp.js
var sum = LibMath.sum, pi = LibMath.pi;
console.log(("2π=" + sum(pi, pi));

2.默认值和通配符(wildcard 野卡片=通配符O(∩_∩)O)

将值标记为默认导出值和值的混入。

ECMAScript 6

// lib/mathplusplus.js
export * from "lib/math"
export var e = 2.71828182864
export default (x) => Math.exp(x)

// someApp.js
import exp, {pi, e} from "lib/mathplusplus"
console.log("e^{π}="+ exp(pi))

ECMAScript 5

// lib/mathplusplus.js
LibMathPP = {};
for (symbol in LibMath)
    if (LibMath.hasOwnProperty(symbol))
        LibMathPP[symbol] = LibMath[symbol];
LibMathPP.e = 2.71828182846;
LibMathPP.exp = function (x) { return Math.exp(x) };

// someApp.js
var exp = LibMathPP.exp, pi = LibMathPP.pi, e = LibMathPP.e;
console.log("e^{π} = " + exp(pi));

你可能感兴趣的:(ECMAScript,6,ES6与ES5的比较)