Function.prototype.before = function (beforefn) {
var __self = this;
return function () {
beforefn.apply(this,arguments);
__self.apply(this,arguments);
};
};
Function.prototype.after = function (afterfn) {
var __self = this;
return function () {
__self.apply(this,arguments);
afterfn.apply(this,arguments);
};
};
var func = function () {
console.log(2);
};
func = func.before(function () {
console.log(1);
}).after(function () {
console.log(3);
});
func();//1 2 3
采用链式函数执行体,before函数中的__self.apply(this)指向的是原函数,after函数中__self.apply(this)指向的是before函数执行体。
Function.prototype.before = function (beforeFn) {
var __self = this;
return function () {
beforeFn.apply(this,arguments);
return __self.apply(this,arguments);//执行原函数
};
};
Function.prototype.after = function (afterFn) {
var __self = this;
return function () {
var ret = __self.apply(this,arguments);//执行原函数
afterFn.apply(this,arguments);
return ret;
};
};
var func = function () {
console.log(2);
};
会先执行after,after中”__self.apply(this,arguments)”会执行原函数,而after的原函数就是before执行的函数,before函数中”beforeFn.apply(this,arguments)”会执行before的参数函数,所以打印出了1,然后”__self.apply(this,arguments)”会执行before的原函数func,所以会打印出2,before执行完毕之后,回到after函数中的”afterFn.apply(this,arguments)”中,会执行after函数的参数函数,所以会打印出3.
func = func.before(function () {
console.log(1);
}).after(function () {
console.log(3);
});
func();//1,2,3