Created
March 14, 2017 12:09
-
-
Save hereisfun/588614dcf954c0dec3a3795cd4f99062 to your computer and use it in GitHub Desktop.
装饰者模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//用途1:组装新功能,不影响原函数 | |
//用途2:动态改变参数。因为都用到了arguments指针,可通过arguments指针修改参数 | |
//注意: 如果原本的函数带有属性,装饰后会丢失属性。因为返回的是一个新的函数。 | |
var before = function(fn, beforefn){ | |
return function(){ | |
beforefn.apply(this, arguments); | |
return fn.apply(this, arguments); | |
} | |
} | |
var after = function(fn, afterfn){ | |
return function(){ | |
var result = fn.apply(this, arguments); | |
afterfn.apply(this, arguments); | |
return result; | |
} | |
} | |
//“污染”Function版 | |
Function.prototype.before = function(beforefn){ | |
var oldfn = this; | |
return function(){ | |
beforefn.apply(this, arguments); | |
return oldfn.apply(this, arguments); | |
} | |
} | |
Function.prototype.after = function(afterfn){ | |
var oldfn = this; | |
return function(){ | |
var result = oldfn.apply(this, arguments); | |
after.apply(this, arguments); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment