1.CommonJS(node环境的写法)
circle.js
const _radius = new WeakMap(); // 弱映射实际上就是字典,字典里面的键是对象,而值可以随意
// 之所以被叫做“弱映射”,是它的键很弱,一旦没有引用就会被垃圾回收机制回收。
class Circle{
constructor(radius){
_radius.set(this,radius);
}
draw(){
console.log('circle with radius:'+_radius.get(this));
}
}
module.exports = Circle;
index.js
const Circle = require('./circle');
const c = new Circle(2);
c.draw();
2.ES6的模块
circle.js
const _radius = new WeakMap(); // 弱映射实际上就是字典,字典里面的键是对象,而值可以随意
// 之所以被叫做“弱映射”,是它的键很弱,一旦没有引用就会被垃圾回收机制回收。
export class Circle{
constructor(radius){
_radius.set(this,radius);
}
draw(){
console.log('circle with radius:'+_radius.get(this));
}
}
index.js
import {Circle} from './circle.js';
const c = new Circle(2);
c.draw();
index.html
<script type="module" src="index.js"></script>
3.ES6工具
在使用现代javascript变成中我们有两类工具:转译器和打包器
转译器:Transpiler,转换(Translator)+编译(Compiler),就是把现代js代码翻译成所有浏览器都能读懂的代码。例如:Babel
打包器:Bundler,打包器就是把很多js文件合并成一个js文件,也就是打包,例如webpack,我们把所有的js文件给webpack,之后它会极大的精简和压缩代码,它会去掉所有的空行、注释、并且会简化一切名称。