Skip to content

ES6代码重构之class简单应用同时支持方法定制 #71

Closed
@LiuYueKai

Description

@LiuYueKai

本次主要应用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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions