javascript中使用 闭包重载函数,记录日志功能

//依据参数个数重载函数
function addMethod (obj,name,fn) {
    var old=obj[name];
    obj[name]=function(){
        if (fn.length===arguments.length) {
            return fn.apply(obj,arguments);
        }else {
            return old.apply(obj,arguments);
        };
    }
}

var obj={};

addMethod(obj,'f1',function(){console.log("f1 0");});
addMethod(obj,'f1',function(a){console.log("f1 1");});
addMethod(obj,'f1',function(a,b){console.log("f1 2");});
addMethod(obj,'f1',function(a,b){console.log("f1 anther 2");});
addMethod(obj,'f1',function(a,b,c){console.log("f1 3");});

obj.f1(1,2);

//在调用真正的函数之前插入函数,实现所谓的AOP功能
Function.prototype.before=function(fn){
    var oldfunc=this;
    return function(){
        fn.apply(this,arguments);
        return oldfunc.apply(this,arguments);
    };
};

//在调用真正的函数之后插入函数,实现所谓的AOP功能
Function.prototype.after=function(fn){
    var oldfunc=this;
    return function(){
        var result= oldfunc.apply(this,arguments);
        fn.apply(this,arguments);
        return result;
    };
}

function func(){
    console.log("func");
}

func=func.before(function (){
    console.log("before 1");
});
func=func.before(function (){
    console.log("before 2");
});

func=func.after(function (){
    console.log("after 1");
});

func=func.after(function (){
    console.log("after 2");
});

func()

 

posted @ 2017-02-22 19:58  瘸腿  阅读(280)  评论(0编辑  收藏  举报