beforefn
Execute a function before a function.
Examples
var before = require('beforefn')
var user = {
name: 'tim oxley',
save: function() {
},
formatName: function() {
this.name = this.name.toUpperCase()
}
}
user.save = before(user.save, user.formatName)
console.log(user.name)
user.save()
console.log(user.name)
Modify arguments
function add(a, b) {
return a + b
}
var addByTen = before(add, function fn(a, b) {
fn.args = fn.args.map(function(x) { return x * 10 })
})
console.log(add(1,2))
console.log(addByTen(1,2))
Fix context
var user = {
name: 'hodor',
speak: function() {
return this.name
}
}
user.speak = before(user.speak, function() {
this.name = this.name[0].toUpperCase() + this.name.slice(1)
}, user)
console.log(user.speak())
user.name = 'hodor'
console.log(user.speak.call({name: 'bran'}))
console.log(user.name)
Adjust Context
var user = {
name: 'hodor',
speak: function() {
return this.name
}
}
user.speak = before(user.speak, function fn() {
fn.context = Object.create(this)
})
user.speak = before(user.speak, function fn() {
this.name = this.name[0].toUpperCase() + this.name.slice(1)
}, user)
console.log(speak())
console.log(user.name)
API Facts
beforefn
returns a new Function.beforefn
ignores return value of before 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.
- Original function
this
context is maintained.
See Also
License
MIT