js装饰者模式

2019-01-31  本文已影响0人  万里独行采花贼

定义:不改变原类型的条件下,丰富原类型的操作。类型一般是类。
例一:经典的aop

Function.prototype.calculate=function(){
        let date1=new Date();
        this.apply(this);
        let date2=new Date();
        console.log('calculate',date2-date1)
    }
    function test(){
        for(let i=0;i<100000;i++){

        }
        console.log("test")
    }
    test.calculate();

例二:

function add1(val){
        return "$"+val;
    }
    function add2(val){
        return val+".00";
    }
    function decorator(){
        this.dep=[]
    }
    decorator.prototype.addDep=function(fn){
        // console.log(this.dep);
        this.dep.push(fn);
    }
    decorator.prototype.outDerivedIn=function(val){
        let maxNumber=this.dep.length-1;
        let dep=this.dep
        function getDepFn(val,number){
            if(number>maxNumber){
                return val
            }
        
            val=dep[number](val);
            return getDepFn(val,number+1);
        }
        return getDepFn(val,0)
    }
    let inst=new decorator();
    inst.addDep(add1);
    inst.addDep(add2);
    console.log(inst.outDerivedIn(6));
上一篇 下一篇

猜你喜欢

热点阅读