[to] apply, call, bind in Javascript

Source: Internet
Author: User

From http://web.jobbole.com/83642/

This article is really difficult to write, because there are numerous articles on the Internet. Coincidence is a few days ago to see an article of teacher Ruan: "For me, the blog is a knowledge management tool, followed by the dissemination of tools." My technical articles are mainly used to sort out the knowledge I don't know. I write only those things that I have not mastered fully, those I am proficient in, often have no motive to write. Showing off is never my motive, curiosity is. "For this sentence, do not agree to more, but also let me make up my mind to write this article, online articles, although most of the copy and paste, and obscure difficult to understand, I hope that through this article, can clearly improve the apply, call, bind understanding, and list some of their magical use to deepen memory.

Apply, call

In JavaScript, call and apply are meant to change the context in which a function is run, in other words, to change the direction of this within the function body.

A major feature of JavaScript is the notion that a function has a "context of definition" and a "runtime context" and a "context can be changed."

First, a chestnut:

function="Red"function() {console.log (this. Color );}} var New  //My color is red

But if we have an object banana= {color: "Yellow"}, we don't want to redefine it say method, then we can use call or apply with Apple's say method:

Banana ="Yellow"//my color is yellow//my color is yellow

So, you can see that call and apply are to change this dynamically, when an object does not have a method (this pest banana no say method), but the others have (this pest Apple has say method), We can use call or apply to manipulate other object methods.

The difference between apply and call

For both apply and call, the function is exactly the same, except that the parameters are accepted in a different way. For example, there is a function defined as follows:

var function (Arg1, arg2) {};

You can invoke the following method:

Func.call (This, arg1, arg2); Func.apply (This, [Arg1, arg2])

Where this is the context you want to specify, he can be any JavaScript object (everything in JavaScript), call needs to pass parameters in order, and apply is to put the parameters in the array.

In JavaScript, the number of arguments for a function is not fixed, so if you want to apply the condition, call is used when your parameters are clearly known.

Use apply when unsure, and then pass in the parameter push into the array. When the number of arguments is indeterminate, the function can also traverse all the arguments by arguments the array.

To consolidate your memory, here are some common uses:

1. Append between arrays

var array1 = [N, "foo", {name "Joe"}, -2458]; var array2 = ["Doe", 555, +]; Array.prototype.push.apply (Array1, array2); /* */

2. Get the maximum and minimum values in the array

var numbers = [5, 458, -215 ]; var // 458 // 458

Number itself does not have the Max method, but with Math, we can use call or apply its methods.

3. Verify that it is an array (provided the ToString () method has not been rewritten)

Functionisarray (obj) {    = = = ' [Object Array] ' ;}

4. Class (pseudo) array using array method

var domnodes = Array.prototype.slice.call (document.getElementsByTagName ("*"));

There is an object structure called a pseudo-array in JavaScript. In particular, arguments objects, as well as calls to getElementsByTagName, document.childnodes and so on, return nodelist objects that are pseudo-arrays. You cannot apply the push, pop, and other methods under the array.

But we can convert the object with the length property to the real array by Array.prototype.slice.call, so that domnodes can apply all the methods under the array.

In-depth understanding of applying apply, call

Below to borrow an interview question, to go deeper to understand the next apply and call.

Define a log method that allows it to proxy the Console.log method, and the common workaround is to:

function log (msg) {    console.log (msg);} Log (//1///1

The above method can solve the most basic requirements, but when the number of incoming parameters is not deterministic, the above method is invalid, this time you can consider using apply or call, notice here how many parameters are indeterminate, so using apply is the best, the method is as follows:

function log () {    console.log.apply (console, arguments);}; Log (//1//1 2

The next requirement is to add a "(app)" prefix to each log message, such as:

// (APP) Hello world

What should be more elegant? This time you need to think that the arguments parameter is a pseudo-array, converted to a standard array by Array.prototype.slice.call, and then using the array method Unshift, like this:

function log () {    var args = Array.prototype.slice.call (arguments);    Args.unshift (' (APP) ');    Console.log.apply (console, args);};

Bind

Finish the Apply and call, and then say bind. The bind () method is similar to apply and call and can also change the direction of this in the function body.

The MDN explanation is that the bind () method creates a new function called a binding function that, when called, binds the binding function to the first parameter of the bind () method as it is created when it is passed into bind () The second and subsequent parameters of the method plus the arguments of the binding function itself are invoked in order as parameters of the original function to invoke the original function.

Take a look directly at how to use it, in common monomer patterns, we usually use _this, that, self, and so on to save this, so that we can continue to reference it after changing the context. Like this:

var foo =1function() {varthis; $ ('. SomeClass '). On (' click ',function(event) {/** *    1});}}

Due to Javascript-specific mechanisms, the context is transitioning to $ ('. SomeClass ') in Eventbind:function () {}. On (' click ', Function (event) {}) changed, the above using variables to save This is all useful and there is nothing wrong with it. Of course, using bind () can solve this problem more gracefully:

var foo =1function() {$ ('. SomeClass '). On (' click ',function (event) {/**/console.log (this//1 }.bind (this));}}

In the above code, bind () creates a function that, when the Click event is bound to be invoked, its this keyword is set to the value passed in (this refers to the parameter passed in when bind () is called). So here we pass in the desired context this (actually foo), into the bind () function. Then, when the callback function is executed, this points to the Foo object. One more simple chestnut:

var function () {console.log (this//  undefinedvar func =//  3

Here we create a new function func, when it is executed by using bind () to create a binding function, it will be set to Foo instead of the global scope as we call Bar ().

The interesting question is, if you have a continuous bind () two times, or a continuous bind () three times, what is the output value? Like this:

 var  bar = function   () {Console.log ( this  .x);}  var  foo = {x:  3  " var  sed = { X:  4}  var  func = Bar.bind (foo). bind (SED); func ();  // ?  var  fiv = {x:  5  " var  func = Bar.bind (foo). bind (SED). bind (FIV); func ();  // ?  

The answer is that the two will still output 3, not the expected 4 and 5. The reason is that in JavaScript, multiple bind () is not valid. For a deeper reason, the implementation of BIND () is equivalent to using a function to wrap a call/apply inside, and the second bind () is equivalent to wrapping the first bind (), so the second bind is not valid.

Apply, call, bind comparison

So what are the similarities and differences between apply, call, and bind? When to use apply, call, and when to use bind. Simple one of the chestnuts:

var obj =bayi,}; var foo =function() {returnthis//  Bayi//Bayi//Bayi

All three outputs are 81, but note that with the bind () method, he has more pairs of parentheses behind him.

That is, the difference is that the bind () method is used when you want to change the context and not execute immediately, but rather when the callback executes. The Apply/call executes the function immediately.

Let's summarize:

    • Apply, call, and bind are all pointers to the This object that is used to change the function;

    • Apply, call, bind the first parameter is the object that this is to point to, that is, the context you want to specify;

    • Apply, call, bind three can use the following parameters to pass the parameter;

    • Bind is to return the corresponding function, which is convenient to call later; apply, call is called immediately.

[to] apply, call, bind in Javascript

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.