Address: https://www.cnblogs.com/xxxxBW/p/4914567.html
Bind method, as the name implies, is the meaning of binding, in the end how to bind then how to use it, the following is to say I understand this method.
Grammar
Fun.bind (This,arg1,arg2,...)
The bind () method creates a new function called a binding function, which is called by the fun method in the This environment
The method can pass in two parameters, the first parameter as this, the second and later arguments as the function parameters call
Instance
1. Create a binding function
1 This. A =1;2 varmodule = {3A:2,4 geta:function () {5 return This. A; 6 }7 };8Module.geta ();//29 Ten varGetA1 =Module.geta; One //The Geta is called externally, at which point this points to the global object AGetA1 ();//1 - - //then bind the GetA1 method to the module environment. the varGetA2 =Geta1.bind (module); -GetA2 ();
As can be seen from the above example, the reason for creating a binding function is that when we invoke certain functions to be called in a particular environment, we are going to put the function in a specific environment, that is, bind the function to a specific desired environment using bind.
2. Let the function have preset parameters
Use the bind () method to have the default initial parameters for the function, which will be the first, and the arguments passed to the binding function will follow them.
1 Function List () {2 //let the class array arguments the method that owns the array slice, this function realizes the simple to convert the class array to the group3 returnArray.prototype.slice.call (arguments);4 }5 6List1,2,3);//[A]7 8 //bind a preset parameter to list 49 varList1 = List.bind (Undefined,4);Ten OneList1 ();//[4] A -List1 (1,2,3);//[4,1,2,3]
Use of 3.setTimeout
Normally, this will point to the global object when calling settimeout, but we need to point to an instance of the class when using the method of the class, so to put this, bind the callback function to facilitate the use of the instance
1 function Fun1 () {2 This. Name =1;3 }4Fun1.prototype.fun2 =function () {5Window.settimeout ( This. Fun3.bind ( This), +);6 }7FUN1.PROTOTYPE.FUN3 =function () {8Console.log ('Name:'+ This. name);//name:19 }Ten varFun =NewFun1 (); OneFun.fun2 ();
4. Quick Method--converting an array of classes into arrays
The first method is to use the Apply method
1 function fun1 () {2 var slice = Array.prototype.slice; 3 return slice.apply (arguments); 4 }5 6 fun1 (1,2,3); [A]
The second approach is to use the call method with the Bind method
1 function fun2 () {2 varUnboundslice =Array.prototype.slice;3 //bind the call method of the function to the array slice method, and then pass the parameter to the call method4 varSlice =Function.prototype.call.bind (unboundslice);5 returnSlice (arguments);6 }7 8Fun2 (1,2,3);//[A]
(RPM) JavaScript method--bind ()