A detailed explanation and summarization of the Call,apply,bind method in JavaScript _javascript skills

Source: Internet
Author: User
Tags arrays closure instance method hasownproperty

The following sections are categorized as follows:

The source of the 1.call/apply/bind method

2.function.prototype.call ()

3.function.prototype.apply ()

3.1: Find the maximum number in the array

3.2: Change the empty element of the array to undefined

3.3: Convert objects that resemble arrays

4.function.prototype.bind ()

5. Objects that bind callback functions

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

The source of the 1.call/apply/bind method

First of all, 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 in fact inherited from the Function.prototype, belong to the instance method.

 Console.log (Function.prototype.hasOwnProperty (' call '))//true
 Console.log (Function.prototype.hasOwnProperty (' Apply ')) True
 Console.log (Function.prototype.hasOwnProperty (' bind '))//true

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

The concept of inheritance will be shared with you later.

2.function.prototype.call ()

The call method of an instance of a function that specifies the point to which this function is to be directed (that is, the scope in which the function executes), and then calls the function in the specified scope. And the function is executed immediately.

Take an example to understand this passage.

 var keith = {
 rascal:123
 };
 var rascal = 456;
 function A () {
 console.log (this.rascal);
 }
 A (); 456
 A.call ();//456
 a.call (null);//456 a.call
 (undefined);//456 a.call
 (this);//456
 A.call (Keith); 123

In the code above, the This keyword in the A function, if pointed to a global object, returns a result of 456. As you can see, if the call method has no arguments, or if the parameter 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, that is, the scope that the function is executing on is the Keith object, 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 parameter is the parameter that needs to be passed when the function is called.

Function Keith (A, b) {
 Console.log (a + b);
 }
Keith.call (NULL, 1, 2); 3

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

One application of the call method is the native method of invoking the object. can also be used to convert class array objects to arrays.

var obj = {};
 Console.log (Obj.hasownproperty (' toString ')); False
 Obj.hasownproperty = function () {return
 true;
 }
 Console.log (Obj.hasownproperty (' toString ')); True
 console.log (Object.prototype.hasOwnProperty.call (obj, ' toString '));//false

In the code above, hasOwnProperty is the method that obj objects inherit, 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 no matter if obj has a method of the same name, it will not affect the result. Note that hasOwnProperty is a method of Object.prototype native objects, and call is a way of inheriting from Function.prototype.

3.function.prototype.apply ()

The Apply method works like the call method, and it also changes this point (the scope where the function executes), and then calls the function in the specified scope. The function is also executed immediately. The only difference is that it receives an array as an argument when the function executes.

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

Look at the nuances of call,apply.

Function Keith (A, b) {
 Console.log (a + b);
 }
 Keith.call (NULL, 2, 3); 5
 keith.apply (null, [2, 3]);//5

In the code above, the first argument is null, pointing to the global scope; the second argument passes in a slightly different form.

The Apply method has the following applications.

3.1: Find the maximum number in the array

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

JavaScript does not provide a way to find the maximum value in an array, and by using the apply and Math.max methods inherited from Function.prototype, the maximum value of the array can be returned.

3.2: Change the empty element of the array to undefined

Using the Apply method, the array constructor is used to transform the empty elements of the arrays into undefined.

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

The difference between an empty element and a undefined is that the Foreach method of an array skips over empty elements, but does not skip undefined and null. So, when you iterate through the internal elements, you get different results.

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

3.3: Convert objects that resemble arrays

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

Console.log (Array.prototype.slice.apply ({0:1,length:1})); [1]
Console.log (Array.prototype.slice.call ({0:1,length:1}));//[1]
Console.log ( Array.prototype.slice.apply ({0:1,length:2})); [1,undefined]
Console.log (Array.prototype.slice.call ({0:1,length:2}));//[1,undefined]
function Keith ( A,B,C) {return
 arguments;
 }
Console.log (Array.prototype.slice.call) (Keith (2,3,4)); [2,3,4]

The arguments for the Call,apply method of the above code are objects, but the return result is an array, which is the purpose of the object being transferred to a group. As you can see from the code above, this method works only if the object being processed must have the length attribute and the corresponding numeric key.

4.function.prototype.bind ()

The Bind method is used to specify this point within the function (the scope in which it is executed), and then return a new function. The Bind method does not perform a function immediately.

var keith = {
 a:1,
 count:function () {
 console.log (this.a++);
 }
 ;
 Keith.count (); 1
 keith.count ();//2
 Keith.count ();//3

In the code above, if THIS.A points to the A attribute within the Keith object, if the method assigns a value to another variable, an error occurs when invoked.

 var keith = {
 a:1,
 count:function () {
 console.log (this.a++);
 }
 ;
 var f = keith.count;
 f (); NaN

In the code above, if you assign the Count method to the F variable, the This object points to no longer a Keith object, but a Window object. and WINDOW.A defaults to undefined, after the increment operation undefined++ equals Nan.

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.

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

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

 var obj = {
 a:100
 };
 var f = keith.count.bind (obj);
 f ();
 f ();//101
 f ();//102

Similarly, we can pass parameters to the Bind method, and the first argument, if null or undefined or this, points to the global environment for the This object inside the function, the second to the parameter required by the call, and the same form as the calling method for passing arguments.

 Function Keith (A, b) {return
 a + b;
 }
 Console.log (Keith.apply (null,[1,4)); 5
 Console.log (Keith.call (null,1,4));//5
 console.log (Keith.bind (NULL, 1, 4));//keith ()
 Console.log (Keith.bind (NULL, 1, 4) ()); 5

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

5. Objects that bind callback functions

In this article JavaScript in this keyword detailed explanation, it is mentioned that if the This object is used in the callback function, then the this object will point to the DOM object, which is the button object. If you want to resolve the this point problem in the callback function, you can use the following method.

var o = {
 f:function () {
 Console.log (this = = O);
 }
 }
 $ (' #button '). On (' click ', Function () {
 o.f.apply (o);
 or O.f.call (o);
 or O.f.bind (o) ();
 });

When the button is clicked, the console will display true. Because the Apply method (or the Call method) not only binds the object in which the function executes, it also executes the function immediately (and the Bind method does not immediately execute, paying attention to the distinction), so it is necessary to write the binding statement in a function body.

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

In fact, these three methods are similar to the problem that specifies this point within the function, but there are formal differences. Readers can use the above examples in three different ways to try to achieve in three ways.

Summarize the Call,apply,bind method:

A: The first argument is a pointer to this within the specified function (the scope at which the function executes), and then the function is called based on the specified scope.

B: All parameters 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 is to execute the function immediately after the call, and the Bind method does not execute immediately, and the function needs to be executed again. A bit of closure.

D: Changing the This object's pointing problem not only has Call,apply,bind method, but also can use that variable to fix the point of this. If you have questions, please visit the This keyword in javascript

Above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

Related Article

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.