beforefn
Execute a function before a function.
var before = // replace user.save with a function that executes// customBeheviour() before every .save callusersave = // roughly equivalent tovar oldSave = useroldSaveuser { return oldSave}
API Facts
beforefn
returns a new Function.- Original arguments will be passed as the second argument to the before function.
- Original function will be passed as the third argument to the before function.
- Properties and prototype are only inherited if you use
before.inherit
. Function arity will not be preserved. - To use with a constructor function, you'll need to use
before.inherit
.
Differences between beforefn 2.x and 3.x
beforefn
3.x no longer inherits properties from the function you're
wrapping. In many cases this is not needed, and the inheritance slows
down beforefn by ~300%. Blame V8.
Examples
var user = name: 'tim oxley' { // save routine } { thisname = thisname } // always calls 'user.formatName' before 'user.save'usersave = console // => tim oxleyuserconsole // => TIM OXLEY
Modify arguments
{ return a + b} var addByTen = console // => 3console // => 30
Fix context
var user = name: 'hodor' { return thisname } userspeak = console // => 'Hodor' // Reset nameusername = 'hodor' // Original function runs in call-time contextconsole // => 'bran' // But the before function runs in context set when definedconsole // => 'Hodor'
Adjust Context
var user = name: 'hodor' { return thisname } userspeak = userspeak = console // => 'Hodor' // the 'this' was altered when the function ran,// but the original object is unmodified due to// the Object.create(this) console // => 'hodor'
Performance
As of beforefn
2.2.0, beforefn
performs comparably to a manually replaced function.
iterations 700000
...
366ms - manually replaced function
299ms - using before function
...
Other runnable benchmarks are located in bench/index.
See Also
License
MIT