Implement Function.bind

Function.bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Question

Implement the Function.bind method

Thought process Pseudocode

  1. The bind method is attached on the Function prototype, and is used to pass an execution context to the function
  2. The bind method takes 2 arguments, one being the context, and an optional parameter of an array of arguments
  3. Both these cases should work
newFunction = oldFuntion.bind(context, arguments)
newFunction()
newFunction = oldFuntion.bind(context)
newFunction(arguments)
  1. Hence the bind method should return a new function in which the arguments must be concatenated and applied using Function.apply
  2. Partially applied arguments, should also work, eg. if a method takes 2 arguments, the following should be valid
function oldFunction(firstArgument, secondArgument) {
}
newFunction = oldFuntion.bind(context, firstArgument)
newFunction(secondArgument)

Solution

Function.prototype.newBind = function (context) {
const currentContext = this;
const currentArguments = Array.prototype.slice.call(arguments, 1); // Dont need the context
return function () {
const args = Array.prototype.slice.call(arguments);
currentContext.apply(context, currentArguments.concat(args))
}
}
this.x = 9; // this refers to global "window" object here in the browser
const module = {
x: 81,
getX: function () { return this.x; }
};
module.getX(); // 81
const retrieveX = module.getX;
retrieveX();
// returns 9 - The function gets invoked at the global scope
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global const x with module's property x
const boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81