前言
这篇通过简单说明ES6 Class和Module这个两个成员。并且用这两个成员制造模块化。
Class说明
Class(类)作用对象模块,也就是一个方法集合,像以前的prototype父类一样,也一样可以通过new来实例,用法基本一样。所以只是换种方法写继承而已。我个人觉得Class加入使代码更加直观,更容易理解。
案例
Class简单一个new实例:
ES5
var name = "tom";
var age = "20";
function model(){}
model.prototype = {
constructor(obj){
this._config = obj;
console.log(obj.name+"年龄"+obj.age)
},
setValue(key,value){
this._config[key]=value;
},
getValue(key){
console.log(this._config[key]?this._config[key]:'no have '+key);
}
}
var example = new model() //tom年龄20
example.constructor({name,age})
example.setValue("sex","man")
example.getValue("sex") //man
example.getValue("day") //no have day
ES6
const name = "tom";
const age = "20";
class model{
constructor(obj){/*就是new命令自动跳用方法。一个类必须要有constructor,如果没定义,有默认添加一个空的。*/
this._config = obj;
console.log(obj.name+"年龄"+obj.age)
}
setValue(key,value){
this._config[key]=value;
}
getValue(key){
console.log(this._config[key]?this._config[key]:`no have ${key}`);
}
}
var example = new model({name,age}) //tom年龄20
example.setValue("sex","man")
example.getValue("sex") //man
example.getValue("day") //no have day
Module说明:
Module就是把js做成模块化的一个核心,就像require.js那样导出和加载一个js。可以把一个js分拆出来加载,也可以整体加载。js一直没有模块概念,Module的加入是为了解决模块化的。
export命令
下面分别输出one,two,three这3个变量。
export.js
exprot var one = "1";
exprot var two = "2";
exprot var three = "3";
import命令
通过export命令定义模块的对外接口后,其他js文件通过import命令来加载文件。
import {one,two,three} from "./export"; //选择对象加载
import * from "./export"; //整体加载
一个完整模块构造模型
parent.js
const name = "tom";
const age = "20";
class Parent{
hw(){
console.log(`hello world`)
}
static obj(){
console.log('obj')/*表示为静态方法不回呗实例继承,而是直接通过类调用。*/
}
}
var parent = new Parent()
parent.hw()//hell world
export{name,age,Parent}
child.js
import {name,age,Parent} from './parent'
class Child extends Parent{
constructor(obj){/*就是new命令自动跳用方法。一个类必须要有constructor,如果没定义,有默认添加一个空的。*/
super()//调用父类的constructor()
this._config = obj;
console.log(obj.name+"年龄"+obj.age)
}
hw(){
console.log("hw")
}
set val(value){
this._config.name = value;
console.log(`name=${value}`)
}
get val(){
console.log(this._config.name);
}
}
Child.obj()//obj 继承父类static方法
var model = new Child({name,age}) //tom年龄20
model.hw()//hw
model.val = "jock"; //name=jock
model.val//jock
附:ES6转换ES2015
http://blog.youkuaiyun.com/rth362147773/article/details/78275551