How can I bind to the right of the function? Example:
var square = Math.pow.bindRight(2);
console.log(square(3)); //desired output: 9
We use the Bind() method to call a function with the this value, this keyword refers to the same object which is currently selected . In other words, bind() method allows us to easily set which object will be bound by the this keyword when a function or method is invoked.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
bind is a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with.
Dynamic binding is the process of determining the method to invoke at runtime rather than compile time. JavaScript accomplishes that with this and the prototype chain. In particular, the meaning of this inside a method is determined at runtime, and the rules change depending on how that method was defined.
Function.prototype.bindRight = function() {
var self = this, args = [].slice.call( arguments );
return function() {
return self.apply( this, [].slice.call( arguments ).concat( args ) );
};
};
var square = Math.pow.bindRight(2);
square(3); //9
You're looking for partial functions, which are convenient shorthands for aliases.
The "classic" way to do what you're asking for is with:
var square = function (x) {
return Math.pow(x, 2);
};
Using partial functions it would be:
var square = Math.pow.partial(undefined, 2);
console.log(square(3));
Unfortunately, Function.prototype.partial
isn't provided in any browser.
Fortunately for you, I've been working on a library of what I consider to be essential JavaScript object oriented functions, methods, classes, etc. This is Function.prototype.partial.js
:
/**
* @dependencies
* Array.prototype.slice
* Function.prototype.call
*
* @return Function
* returns the curried function with the provided arguments pre-populated
*/
(function () {
"use strict";
if (!Function.prototype.partial) {
Function.prototype.partial = function () {
var fn,
argmts;
fn = this;
argmts = arguments;
return function () {
var arg,
i,
args;
args = Array.prototype.slice.call(argmts);
for (i = arg = 0; i < args.length && arg < arguments.length; i++) {
if (typeof args[i] === 'undefined') {
args[i] = arguments[arg++];
}
}
return fn.apply(this, args);
};
};
}
}());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With