A detailed and summary of Call,apply,bind methods in JavaScript

Source: Internet
Author: User
Tags hasownproperty

In the JavaScript this keyword detailed article, we talked about the following to make a simple review:

The meaning of a 1.this object is to point to properties and methods in the current object.

The variability of the 2.this point. This points to the global when the global scope is used, and this points to the object when you use this in an object, and this points to the next object when you assign an object's method to another object.

3.this is used in a global environment, used in constructors, and used in methods of objects.

4.this usage Note, the most important point is to avoid multi-layer nesting using the This object.

With a little bit of understanding of the This keyword, it is known that this object point will change frequently, which can cause some unintended effects. JavaScript provides, call apply and bind These three methods, to toggle/pin this the pointing.

The following sections are categorized as follows:

Source of the 1.call/apply/bind method

2.function.prototype.call ()

3.FUnction.prototype. Apply ()

3.1: Find out the maximum number in the array

3.2: Change the empty element of the array to undefined

3.3: Converting an array-like object

4.FUnction.prototype. Bind ()

5. object that binds the callback function

The relation and difference of 6.call,apply,bind method

Source of the 1.call/apply/bind method

  First, when using the Call,apply,bind method, it is necessary to know where these three methods come from. Why is it possible to use these three methods?

Call,apply,bind these three methods are actually inherited from the Function.prototype, belong to the instance method.

1     console.log (Function.prototype.hasOwnProperty (' call '))//true2     Console.log ( Function.prototype.hasOwnProperty (' Apply '))//true3     console.log (Function.prototype.hasOwnProperty (' bind ')) True

All of the above code returns TRUE, indicating that three methods are inherited from Function.prototype. Of course, ordinary objects, functions, and arrays all inherit the three methods in the Function.prototype object, so these three methods can be used in objects, arrays, functions.

The concept of inheritance will be shared with you in the future.

2.function.prototype.call ()

A method of an instance of a function call that specifies the point of this within the function (that is, the scope in which the function executes), and then invokes the function in the scope specified. And the function is immediately executed.

Take a look at an example to understand this passage.

1     var keith = {2         rascal:123 3     }; 4  5     var rascal = 456; 6  7     function A () {8         Console.lo g (this.rascal); 9     }10     A ();//45612     A.call ();//45613     a.call (null);//45614     a.call (undefined);//45615     A.call (this);//45616     A.call (Keith);//123

In the above code, the This keyword in the a function, if it points to a global object, returns a result of 456. As you can see, if the call method has no arguments, or if the argument is null or undefined or this, it is equivalent to pointing to the global object. If you use the call method to point the This keyword to the Keith object, which is where the function executes, the Keith object is returned, and the result is 123.

  The call () method can pass two parameters. The first parameter is the pointer to this within the specified function (that is, the scope in which the function executes), and the second argument is the one that needs to be passed when the function is called.

1     function Keith (A, b) {2         console.log (A + B), 3     }4 5     keith.call (NULL, 1, 2);//3

The first parameter is required, which can be null,undefined,this, but cannot be empty. Setting to Null,undefined,this indicates that the function Keith is at the global scope at this time. The second parameter must be added one at a. It must be added as an array in apply.

  One application of the call method is to invoke the native method of the object. You can also use to convert class array objects to arrays.

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     Console.log (Object.prototype.hasOwnProperty.call (obj, ' toString ')); False

In the above code, hasOwnProperty is the method that the Obj object inherits, and if this method is overwritten, it will not get the correct result. The call method solves this method by placing the original definition of the hasOwnProperty method on the Obj object, so that the result is not affected by any method of the same name on obj. It is important to note that hasOwnProperty is a method of Object.prototype native objects, and call is a method that inherits from Function.prototype.

  

3.FUnction.prototype. Apply ()

  applyA method is call similar to a method, and this It also changes direction (the scope where the function executes), and then invokes the function in the specified scope. The function is also executed immediately. The only difference is that it takes an array as a parameter when the function executes.

  applyThe first parameter of the method is also the this object to point to, and if set to null or undefined or this, it is equivalent to specifying the global object. The second argument is an array in which all the members, in turn, are arguments, passing in the original function upon invocation. The parameters of the original function call must be added to the method, but in the apply method, it must be added as an array.

Take a look at call,apply nuances.

1     function Keith (A, b) {2         console.log (A + B), 3     }4 5     keith.call (NULL, 2, 3);//56     keith.apply (NULL, [ 2, 3]); 5

In the above code, the first parameter is null, points to the global scope, and the second parameter passes in a slightly different form.

The Apply method has the following applications.

3.1: Find out the maximum number in the array

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

In JavaScript, there is no way to find the maximum value in an array, and with the apply and Math.max methods inherited from Function.prototype, you can return the maximum value of the array.

  

3.2: Change the empty element of the array to undefined

  Using the apply array constructor, the empty elements of the array are transformed into undefined by means of the method.

1 Console.log (array.apply (null, [1,, 3])); [1, Undefined, 3]

undefinedthe difference between empty elements is that the method of the array forEach skips the empty elements, but does not skip them undefined和null . As a result, you get different results when iterating through the inner elements.

    var a = [1,, 3];    A.foreach (function (index) {        console.log (index);//1,3, skipping empty elements.    })    Array.apply (null,a). ForEach (function (index) {        console.log (index);    1,undefined,3  , set the empty element to undefined    })

3.3: Converting an array-like object

  In addition, an array slice -like object, such as an object, can be converted to a real array using the method of the Arrays object arguments . Of course, an important application of the slice method is to convert an array-like object into a true array. Both call and apply can implement the application.

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]

The arguments to the Call,apply method of the above code are all objects, but the returned result is an array, which is why the object is being transferred to a group. As you can see from the above code, this method works by assuming that the object being processed must have the length property and the corresponding numeric key.

  

4.FUnction.prototype. Bind ()

  bindMethod 用于指定函数内部的this指向(执行时所在的作用域) , and then returns a new function. The Bind method does not immediately execute a function.

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

In the above code, if THIS.A points to the A property inside the Keith object, if the method assigns a value to another variable, it will be called with an error.

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

In the above code, if the Count method is assigned to the F variable, then the this object points to the Window object, which is no longer a Keith object. The WINDOW.A defaults to undefined, and undefined++ equals nan after the increment operation.

To solve this problem, you can use the Bind method to bind the this in the Keith object to the Keith object, or call it directly.

1     var f = keith.count.bind (Keith), 2     f ();//13     f ();//24     f ();//3
1     Keith.count.bind (Keith) ()//12     Keith.count.bind (Keith) ()//23     Keith.count.bind (Keith) ()//3

Of course, this can also be bound to other objects.

1     var obj = {2         a:1003     };4     var f = keith.count.bind (obj); 5     f ();//1006     f ();//1017     f ();// 102

Similarly, we can also pass parameters to the Bind method, if the first argument is null or undefined or this, the this object inside the function points to the global environment, the second is the parameter required for invocation, and the pass parameter is the same as the call method.

1     function Keith (A, b) {2         return a + b;3     }4     console.log (keith.apply (null,[1,4]));//55     Console.log (Keith.call (null,1,4));     Console.log (Keith.bind (NULL, 1, 4)),//keith () 7     console.log (Keith.bind (NULL, 1, 4) ());//5

In the above code, you can see the difference between the three call,apply,bind:call and Apply methods are executed immediately after the invocation. And after the bind call is returned the original function, need to call again before the line, a bit like the taste of closures, if the closure concept is unfamiliar, you can browse the two articles: javascript--function parameters and closures--detailed, JavaScript important concept-closure-in-depth understanding.

5. Object that binds the callback function

  In this article, JavaScript, this keyword is explained in detail, that if you use the This object in the rollback function, the This object will point to the DOM object, which is the button object. If you want to resolve this point in the callback function, you can use the following method.

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         //or O.f.call (o);         //or O.f.bind (o) ();     

When you click the button, the console will be displayed true . Because apply the method (or call method) not only binds the object where the function executes, but also executes the function immediately (and the Bind method does not execute immediately, notice the difference), the binding statement has to be written in a function body.

The relation and difference of 6.call,apply,bind method

  In fact, to specify the internal function of this point of the problem, these three methods are similar, but there is a formal difference. Readers can use the above example in three ways to try to achieve in three ways.

Summarize the Call,apply,bind method:

A: The first parameter is the pointer to this within the specified function (the scope where the function executes), and then the function is called according to the specified scope.

B: All arguments can be passed when the function is called. The Call,bind method needs to be passed in directly, and the Apply method needs to be passed in as an array.

The C:call,apply method executes the function immediately after the call, and the Bind method does not execute immediately, and the function needs to be executed again. It smells like a little closure.

D: Changing the point of this object not only has the Call,apply,bind method, you can also use that variable to pin the point of this. If in doubt, please visit JavaScript's this keyword

A detailed and summary of Call,apply,bind methods in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.