Implement 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
- The bind method is attached on the Function prototype, and is used to pass an execution context to the function
- The bind method takes 2 arguments, one being the context, and an optional parameter of an array of arguments
- Both these cases should work
newFunction = oldFuntion.bind(context, arguments)newFunction()newFunction = oldFuntion.bind(context)newFunction(arguments)
- Hence the bind method should return a new function in which the arguments must be concatenated and applied using Function.apply
- 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 contextreturn 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 browserconst module = {x: 81,getX: function () { return this.x; }};module.getX(); // 81const 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 xconst boundGetX = retrieveX.bind(module);console.log(boundGetX()); // 81