What is function-bind?
The function-bind npm package is a polyfill for Function.prototype.bind, which is a method in JavaScript used to create a new function that, when called, has its 'this' keyword set to the provided value. The bind method can also prepend a fixed set of arguments to the arguments passed to the bound function when it is called.
What are function-bind's main functionalities?
Binding a function to a context
This feature allows you to bind a function to a specific context, so that the 'this' keyword inside the function refers to the provided context object.
var bind = require('function-bind');
function greet() {
return 'Hello, ' + this.name;
}
var context = { name: 'Alice' };
var boundGreet = bind.call(greet, context);
console.log(boundGreet()); // 'Hello, Alice'
Prepending arguments to the bound function
This feature allows you to create a new function by not only binding it to a context but also prepending arguments to it. When the new function is called, these arguments are passed in front of any other provided arguments.
var bind = require('function-bind');
function add(a, b) {
return a + b;
}
var addOne = bind.call(add, null, 1);
console.log(addOne(2)); // 3
Other packages similar to function-bind
lodash.bind
lodash.bind is a method from the Lodash library that provides similar functionality to function-bind. It allows you to bind functions to a context and optionally prepend arguments. Lodash offers a more extensive set of utility functions, whereas function-bind focuses solely on the bind functionality.
function-bind
Implementation of function.prototype.bind
Example
I mainly do this for unit tests I run on phantomjs.
PhantomJS does not have Function.prototype.bind :(
Function.prototype.bind = require("function-bind")
Installation
npm install function-bind
Contributors
MIT Licenced