ES6 Class Module模組化 案例
阿新 • • 發佈:2019-01-22
前言
這篇通過簡單說明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