AMD、CMD、ES6模块化规范
// 1、闭包立即执行函数 var module = (function(){ var name = 'xiaoming'; var print = () => console.log(name) return { print: print}; })(); module.print(); // 2、AMD规范(保存为math.js) define(function (){ var add = (x,y) => x+y return {add: add}; }); // 引用(需要require.js) require(['math'], (math) => console(math.add(3, 4))) // 3、CMD规范(保存为math.js) var square = (x) => x * x var diag = (x, y) => Math.sqrt(square(x) + square(y)) exports.square = square; exports.diag = diag; // 引用 var math = require("./math.js"); console.log(math.square(5)); console.log(math.diag(3, 4)); // 4、ES6规范(保存为module.js) export default function fn1(msg) { //方式1 console.log(msg) } export function fn2(msg) { //方式2 console.log(msg) } function fn3(msg) { //方式3 console.log(msg) } export {fn3} // 默认导入(只可以导入一个方法) import fn1 from './module.js' fn1('fn1') // 按需导入 import {fn2,fn3} from './module.js' fn2('fn2') fn3('fn3') // 全部导入 import * as fn from './module.js' fn.fn2('fn.fn2') fn.fn3('fn.fn3')