call, apply, bind usage and differences

call, apply, bind usage and differences: https://www.cnblogs.com/Jade-Liu18831/p/9580410.html

 

Source 1.call/apply/bind method

  First, the use of call, apply, when the bind method, we need to know exactly where these three methods come from? Why you can use these three methods?

  call, apply, bind these three methods are in fact inherited from Function.prototype of belonging to an instance method.

1     console.log(Function.prototype.hasOwnProperty('call')) //true
2     console.log(Function.prototype.hasOwnProperty('apply')) //true
3     console.log(Function.prototype.hasOwnProperty('bind')) //true

  The above code returns a true, it indicates that the three methods are inherited from the Function.prototype. Of course, ordinary objects, functions, arrays inherit three methods Function.prototype objects, so these three methods can be used in objects, arrays, functions.

  Concept of inheritance, will share with you later.

 

2.Function.prototype.call()

  Function instance callmethods, the function can be specified inside this point (i.e., where the scope of a function performed), then the specified scope, the function call. And performs the function immediately.

  A good look at an example to understand this passage.

Copy the code
Copy the code
 1     var keith = {
 2         rascal: 123
 3     };
 4 
 5     var rascal = 456;
 6 
 7     function a() {
 8         console.log(this.rascal);
 9     }
10 
11     a(); //456
12     a.call(); //456
13     a.call(null); //456
14     a.call(undefined); //456
15     a.call(this); //456
16     a.call(keith); //123
Copy the code
Copy the code

  In the above code, the this keyword a function of, if the global object, returns a value of 456. Can be seen that, if the method does not call parameter or parameter is null or undefined or the this, it is equivalent to the global object. If this keyword call method keith target point, where the scope is performed as a function of the time keith object 123 returns a value.

  call () method can pass two parameters. The first parameter is a function specified in this internal point (i.e. where the scope of a function execution), the second parameter is a parameter of the function call need to pass.

1     function keith(a, b) {
2         console.log(a + b);
3     }
4 
5     keith.call(null, 1, 2); //3

  The first parameter is required, it may be null, undefined, this, but can not be empty. Is set to null, undefined, this indicates that the function keith now in global scope. The second parameter must be added one by one. And it must be added in the form of an array apply in.

  Application call a method of native method calls the object. It may also be used to convert an array of array-like object.

Copy the code
Copy the code
 1     var obj = {};
 2     console.log(obj.hasOwnProperty('toString')); //false
 3 
 4     obj.hasOwnProperty = function() {
 5         return true;
 6     }
 7 
 8     console.log(obj.hasOwnProperty('toString')); //true
 9 
10     console.log(Object.prototype.hasOwnProperty.call(obj, 'toString')); //false
Copy the code
Copy the code

  The above code, the object obj hasOwnProperty is inherited methods, if this method is once covered, can not obtain the correct result. call ways to solve this method, it will put the original definition hasOwnProperty method of execution on the object obj, obj on this matter there is no method of the same name, it will not affect the results. Note that, hasOwnProperty method Object.prototype native objects, and the call is inherited from Function.prototype method.

  

3.Function.prototype.apply()

  applyFunction and methods callsimilar methods, but also to change the thispoint (where the scope when the function is executed), and then specify the scope, the function is called. It will also perform this function immediately. The only difference is that it receives an array as a function of the execution parameter.

  applyThe first argument of the method is thisthat the object pointed to, or undefined or set to null if the this, it is equivalent to specifying the global object. The second parameter is an array, all members of the array as a parameter in turn, passed the original function when calling. Parameters of the original function, in callneed of a method for adding one, but in the applyprocess, must be added in the form of an array.

  Look at the nuances call, apply the.

Copy the code
Copy the code
1     function keith(a, b) {
2         console.log(a + b);
3     }
4 
5     keith.call(null, 2, 3); //5
6     keith.apply(null, [2, 3]); //5
Copy the code
Copy the code

  In the above code, the first parameter is null, the global scope to point; second parameter passed in the form of slightly different.

  apply method has the following applications.

 

  3.1: Find out the maximum number of array

1     var a = [2, 4, 5, 7, 8, 10];
2 
3     console.log(Math.max.apply(null, a)); //10
4     console.log(Math.max.call(null,2, 4, 5, 7, 8, 10)); //10

  Javascript is not to find ways to provide the maximum value of the array using a combination of inherited from Function.prototype apply and Math.max method, you can return the maximum value of the array.

  

  3.2: empty element of the array becomes undefined

  By applythe method, using the Array constructor of the array element becomes empty undefined.

1 console.log(Array.apply(null, [1, , 3])); // [1, undefined, 3]

  Empty elements and undefinedthe difference is that the array forEachmethod will skip the empty element, but does not skip undefined和null. Therefore, when traversing the internal elements, you get different results.

Copy the code
Copy the code
    A = var [. 1,,. 3]; 
    a.forEach (function (index) { 
        the console.log (index);. // l, 3, skip empty element 
    }) 

    Array.apply (null, A) .forEach (function (index) { 
        the console.log (index); ////. 1, undefined,. 3, the empty element is set to undefined 
    })
Copy the code
Copy the code

 

  3.3: Conversion of the array-like objects

  Further, by using an array of objects sliceobjects (such method can be a similar array of argumentsobjects) into the real array. Of course, an important application slice method is to array-like object into a true array. call and apply application that can be achieved.

1     console.log(Array.prototype.slice.apply({0:1,length:1}));    //[1]
2     console.log(Array.prototype.slice.call({0:1,length:1}));    //[1]
3     console.log(Array.prototype.slice.apply({0:1,length:2}));    //[1,undefined]
4     console.log(Array.prototype.slice.call({0:1,length:2}));    //[1,undefined]
1     function keith(a,b,c){
2         return arguments;
3     }
4 
5     console.log(Array.prototype.slice.call(keith(2,3,4)));    //[2,3,4]

  Call the above code, Apply parameters are object method, but the results are returned array, which functions as a transfer object into an array of purposes. Can be seen from the above code, the method works on the premise that the object to be treated must have length property, and the corresponding number key.

 

  

4.Function.prototype.bind()

  bindThe method 用于指定函数内部的this指向(执行时所在的作用域)then returns a new function. bind method does not perform a function immediately.

Copy the code
Copy the code
 1     var keith = {
 2         a: 1,
 3         count: function() {
 4             console.log(this.a++);
 5         }
 6     };
 7 
 8     keith.count(); //1
 9     keith.count(); //2
10     keith.count(); //3
Copy the code
Copy the code

  In the above code, if this.a inwardly directed keith a property of the object, if the method of assignment to another variable, an error occurs when calling.

Copy the code
Copy the code
1     var keith = {
2         a: 1,
3         count: function() {
4             console.log(this.a++);
5         }
6     };
7 
8     var f = keith.count;
9     f(); //NaN
Copy the code
Copy the code

  The above code, if the count method assigned to the variable f, then this is no longer keith object points to the object, but rather the window object. The undefined ++ after window.a default is undefined, incrementing operation is equivalent to NaN.

  To solve this problem, you can use the bind method, keith objects inside this keith bound to an object, or a direct call.

1     var f = keith.count.bind(keith);
2     f(); //1
3     f(); //2
4     f(); //3
1     keith.count.bind(keith)() //1
2     keith.count.bind(keith)() //2
3     keith.count.bind(keith)() //3

  Of course, this can also bind to other objects.

Copy the code
Copy the code
1     var obj = {
2         a: 100
3     };
4     var f = keith.count.bind(obj);
5     f(); //100
6     f(); //101
7     f(); //102
Copy the code
Copy the code

  Similarly, we can also pass parameters to the bind method, the first parameter to the global environment if this object is null or undefined or this, the interior will function; the second parameter is invoked when needed, and passes the parameters in the form of call the same method.

Copy the code
Copy the code
1     function keith(a, b) {
2         return a + b;
3     }
4     console.log(keith.apply(null,[1,4])); //5
5     console.log(keith.call(null,1,4)); //5
6     console.log(keith.bind(null, 1, 4)); //keith()
7     console.log(keith.bind(null, 1, 4)()); //5
Copy the code
Copy the code

  In the above code, it can be seen Call, apply, three bind distinction: Call and apply method are performed immediately after the call. But after the bind call is a return to the original function, called once again need the job, a bit like the taste of closure, if not familiar with the concept of closure, you can browse these two articles: JavaScript - function parameters and closures - Detailed , javascript important concept - closure - in-depth understanding .

 

The binding callback objects

  In this article this keyword's Detailed javascript , there is talk that if the use of this function object back out, then this will point to the object is a DOM object, which is the button object. If you want to solve the problem callback function this point, you can use the following method.

Copy the code
Copy the code
 1     var o = {
 2         f: function() {
 3             console.log(this === o);
 4         }
 5     }
 6 
 7     $('#button').on('click', function() {
 8         o.f.apply(o);
 9         //或者 o.f.call(o);
10         //或者 o.f.bind(o)();
11     });
Copy the code
Copy the code

  After clicking the button, the console will be displayed true. As the applymethod (or callmethods) only where the binding object when the function is executed, will immediately execute the function (and bind method is not performed immediately, note the difference), and therefore had to bind the statement written in a function body.

 

Links and differences 6.call, apply, bind method

  In fact, this is used to specify the function pointed to internal problems, these three methods are similar, but there is a difference in form. Readers can use the above example are three ways to try to achieve in three ways.

  To sum up call, apply, bind method:

  a: The first parameter is a function specified in this internal point (where the scope is performed when the function), then the specified scope, the function call.

  b: the parameters can be passed in the function call. call, bind method requires direct incoming, and apply methods need to pass in the form of an array.

  c: call, apply method is to perform the function immediately after the call, and bind method is not performed immediately, the function needs to be re-executed again. It closed a little taste of the package.

  d: change point problem this object not only call, apply, bind method, this may be a fixed point of use that variable.

Guess you like

Origin www.cnblogs.com/bydzhangxiaowei/p/11525166.html