Skip to content

Instantly share code, notes, and snippets.

@GeekSnail
Last active February 26, 2019 06:58
Show Gist options
  • Save GeekSnail/5d9c1d84eed6aec86e97e75dda7d58e9 to your computer and use it in GitHub Desktop.
Save GeekSnail/5d9c1d84eed6aec86e97e75dda7d58e9 to your computer and use it in GitHub Desktop.
Function.prototype.before = function (beforefn) {
var _self = this; //保存原函数引用
console.log('call before', this)
return function () { //返回包含了原函数和新函数的"代理函数"
console.log('call before, return', this, 'arg', arguments)
beforefn.apply(this, arguments); //执行新函数,修正this
console.log('call before return return', this, 'arg ',arguments, '_self ', _self)
return _self.apply(this, arguments); //执行原函数
}
};
Function.prototype.after = function (afterfn) {
var _self = this;
console.log('call after', this)
return function () {
console.log('call after return', this, 'arg ', arguments, '_self ', _self)
var ret = _self.apply(this, arguments);
console.log('call after return return', this, 'arg', arguments)
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();
/*
call before ƒ () {
console.log("2")
}
call after ƒ () { //返回包含了原函数和新函数的"代理函数"
console.log('call before, return', this, 'arg', arguments)
beforefn.apply(this, arguments); //执行新函数,修正this
console.log('call before return return', this, 'arg ',ar…
call after return Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} arg Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]callee: ƒ ()length: 0Symbol(Symbol.iterator): ƒ values()__proto__: Object _self ƒ () { //返回包含了原函数和新函数的"代理函数"
console.log('call before, return', this, 'arg', arguments)
beforefn.apply(this, arguments); //执行新函数,修正this
console.log('call before return return', this, 'arg ',ar…
call before, return Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} arg Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
1
call before return return Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} arg Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ] _self ƒ () {
console.log("2")
}
2
call after return return Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …} arg Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment