Skip to content

Bind context to the given function and preserves her name. Or set new name of the given function. It also handles `.toString` correctly.

License

Notifications You must be signed in to change notification settings

tunnckoCore/bind-context

Repository files navigation

Bind context to a function and preserves her name. Can be used to change name of a function. The toString also works correctly.

code climate standard code style travis build status coverage status dependency status

Install

npm i bind-context --save

Usage

For more use-cases see the tests

const bindContext = require('bind-context')

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 new name for it.
  • name {String=}: Name for the new function (optional, can be used to rename functions).
  • returns {Function}: New function which will have ctx 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

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.

tunnckoCore.tk keybase tunnckoCore tunnckoCore npm tunnckoCore twitter tunnckoCore github

About

Bind context to the given function and preserves her name. Or set new name of the given function. It also handles `.toString` correctly.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published