函数链式调用+Proxy实现版本

69 阅读1分钟

1.函数链式调用:每个函数都要返回this,以便链式使用this对象的各类属性

function obj(value){
    this.value = value;
    this.addValue = function(){
        this.value+=1;
        return this;
    }
    this.multiValue = function(){
        this.value*=2;
        return this;
    }
    this.getValue = function(){
        return this.value;
    }
}
​
let myObj = new obj(2);
console.log(myObj.multiValue().addValue().getValue());

2.Proxy实现版本:需要每次Proxy触发handler的get属性,都要返回这个Proxy,在这之后再调用(读取)这个Proxy就能起到链式调用的效果

addValue = function(value){
    return value+=1;
}
multiValue = function(value){
    return value*=2;
}
​
function chain(value){
    let handler = {
        get(obj,prop){
            // console.log(this)
            if(prop==='end'){
                return obj.value;
            }
            if(typeof global[prop] === 'function'){
                obj.value=global[prop](obj.value);
                return myProxy;
            }
        }
    }
    let myProxy = new Proxy({value},handler);
    return myProxy;
}
​
console.log(chain(2).multiValue.addValue.end);