ES6代码重构之class简单应用同时支持方法定制
LiuYueKai opened this issue · comments
本次主要应用ES6中的class、import、export来进行优化,同时使用call方法的应用来实现定制。
getById.js
// 定义基础方法
var getById = function(id){
return this.attrs[id];
}
export{
getById
}
getByCode.js
//暴露的方法
import {getById} from './getById'
var getByCode = function(code){
id = code;
// return this.getCompById(id) // 挂载getById的情况下直接调用
return getCompById.call(this,id) //通过call来实现在不挂载getCompById的情况下指定作用域
}
export{
getByCode
}
add.js
var add = function(id,value){
this.attrs = {};
this.attrs[id] = value;
}
export{
add
}
index.js
import {getByCode} from './getByCode'
import {add} from './add'
class App {
constructor(){
// 在构造方法中添加function,相当于在prototype上添加方法
this.getByCode = getByCode;
this.add = add;
}
}
window.App = App;
export {App}
index.html
//引入产出的js之后调用下面的js代码进行测试
var a = new App();
a.add('id1',"value1");
var v1 = a.getByCode('id1'); //返回value1
不知所云