bind is similar to call, for example, an acceptable parameter is divided into two parts, and the first parameter is the object that acts as this in the context of the function at execution time.
There are two of different points:
The return value of ①bind is a function
Is thisfunction func (name,id) {Console.log (name,id,this), which takes obj as the context; var obj = "Look here";//Do not add func ("", "--");//Use BIND is the function that returns change context this after var a = Func.bind (obj, "bind", "--"); /Use call is to change the context of this and execute the function var b = func.call (obj, "call", "--");
Results:
There are also differences in the use of parameters behind ②
function f (a,b,c) {console.log (a,b,c);} var f_extend = F.bind (null, "extend_a") F ("A", "B", "C")//This will be output--a B cf_extend ("A", "B", "C")//here will output--extend_a A b F_extend ("B", "C")//This will output--extend_a B cf.call (null, "extend_a")//here will output--extend_a undefined undefined
This difference is not very good understanding
Call is to pass in the second and later arguments as an argument to the F method.
Bind, though, also gets the second and later arguments for subsequent execution of the method, but the arguments passed in the F_extend are based on the arguments passed in the bind.
This code is equivalent to the following operation var f_extend = F.bind (null, "extend_a")//↓↓↓var f_extend = function (b,c) {return f.call (null, "extend_a", b , c);}
To give a scenario: for example, there is now a way to do the processing according to different file types, and bind can create a simplified version of the processing method
function Filedealfunc (type,url,callback) {if (type== "txt") {...} else if (type== "xml") {...} .....} var Txtdealfunc = Filedealfunc.bind (this, "TXT");//This makes it easier to use some filedealfunc ("txt", xxurl,func); Original Txtdealfunc (Xxurl,func); Right now
The following are compatible processing
if (! Function.prototype.bind) {Function.prototype.bind = Function (obj) {var _self = this, args = Argumen Ts return function () {_self.apply (obj, Array.prototype.slice.call (args, 1)); } }}
The difference between bind and call