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);** //这一块不是应该输出2么
afterfn.apply(this, arguments);
return ret;
}
}
var func = function() {
console.log(2);
}
func = func.before(function() {
console.log(1);
}).after(function() {
console.log(3);
})
func();
程序输出结果是 1, 2 ,3 . 但为啥不是 12 23, 因为Function.prototype.after里面第一步就是 _self.apply() ?
稍微改一下,看你看得懂不
javascript
var func = function() { console.log(2); } func = func.before(function() { console.log(1); }); func(); func = func.after(function() { console.log(3); }); func();
输出
1 2 1 2 3