bind-context
v2.0.2
Published
Bind context to a function and preserves her name. Can be used to change name of a function. The toString also works correctly.
Downloads
12
Readme
bind-context
Bind context to a function and preserves her name. Can be used to change name of a function. The toString also works correctly.
Install
npm i bind-context --save
Usage
For more use-cases see the tests
const bindContext = require('bind-context')
bindContext
Bind context to a function and preserve her name.
Params
ctx
{Object|Function}: The context to pass bind or function.fn
{Function|String=}: Function to bind context to, or newname
for it.name
{String=}: Name for the new function (optional, can be used to rename functions).returns
{Function}: New function which will havectx
bound and correct.toString
.
Example
var inspect = require('util').inspect
var bindContext = require('bind-context')
function hello () {
// `this` context is `{foo: 'bar'}`
return this.foo
}
// just returns same function
// as regular `.bind`, but also
// preserves the name of given function
var hi = bindContext({foo: 'zzz'}, hello, 'bar')
console.log(inspect(hi)) // => [Function: bar]
console.log(hi) // => [Function: bar]
console.log(hi()) // => 'zzz'
console.log(hi.toString()) // => function bar () { ... code ... }
console.log(hi.name) // => 'bar'
Signatures
bindContext.call(Object, Function) // preserves name
bindContext.call(Object, Function, String) // changes name
bindContext(Object, Function) // preserves name (with context)
bindContext(Object, Function, String) // changes name (with context)
bindContext(Function) // preserves name (no context, saves Function's context if it has)
bindContext(Function, String) // changes name (no context, saves Function's context if it has)
Related
- function-arguments: Get arguments of a function, useful for and used in dependency… more | homepage
- function-equal: Compares two functions, are they equal? Checks their names, bodies and… more | homepage
- get-fn-name: Get function name with strictness and correctness in mind. Also works… more | homepage
- parse-function: Parse a function, arrow function or string to object with name,… more | homepage
- rename-function: Rename a given function. Tries to be cross-platform and guaranteed. Useful… more | homepage
- smart-bind: Smarter binding of function with some context. It uses .apply instead… more | homepage
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
But before doing anything, please read the CONTRIBUTING.md guidelines.