1. Bind
Bind () is a new method in ECMAScript5, which is primarily used to bind a function to an object. When calling the bind () method on the function f () and passing in an object o as a parameter, this method returns a new function that differs from the original function f () only that the this parameter points to a specific object o.
Examples are as follows:
function f (y) { returnthis. x + y; } var obj = {x:1}; var newfun = f.bind (obj); Newfun (2); // =>3
Analog Basic usage:
if(!Function.prototype.bind) {Function.prototype.bind=function(/*o*/){ varobj = arguments[0]; varSelffun = This; return function(/*args*/){ returnselffun.apply (obj, arguments); }; };}functionF (y) {return This. x +y}varobj = {X:1};varNewfun =f.bind (obj); Console.log (Newfun (2));//=>3
What is the curry? If you fix some parameters of a function, you will get a new function that accepts the remaining arguments. The bind () method in ECMAScript5 can not only bind the this in a function to a particular object, but also bind the function's parameters to a specific value. This application of Bing () became curry (curring).
Examples are as follows:
var function (x, Y) {returnthis. z}; var obj = {z:1}; var newfun = Sum.bind (obj, 1); Console.log (Newfun (1)); // =>3
Analog currying Usage:
if(!Function.prototype.bind) {Function.prototype.bind=function(/*o, args*/){ //Save the function you want to bind varSelffun = This; //to save the binding's arguments varobj = Arguments[0];//binds the first parameter to this varBoundargs = arguments;//bind the following arguments to the previous arguments of the function //The bind method returns a function (closure) //this closure is to access Selffun, Boundargs, obj in the external function. return function(/*Argsleft*/){ varargs = [];//Create a real parameter group vari; for(i = 1; i < boundargs.length; i++) {//the arguments for the push bindingArgs.push (Boundargs[i]); } for(i = 0; i < arguments.length; i++) {//Push remaining argumentArgs.push (Arguments[i]); } //inside the closure to access variables defined within the external function returnselffun.apply (obj, args); }; }}functionSum (x, y) {returnX + y + This. z};varobj = {Z:1};varNewfun = Sum.bind (obj, 1); Console.log (Newfun (1));//=>3
Bind&currying