The similarities and differences between call (), apply (), and bind ()

Source: Internet
Author: User

Same point:

Change the direction of this;

    var a = {        name:"Meatball",        fn:function() {            Console.log (this  . Name);        }    }     var b = A.fn;    B ()//undefined    b.call (a);   Meatball    b.apply (a);   Meatball    B.bind (a);   not be printed

Different points:

Both 1,call and apply are executed immediately , and bind returns a function ;

    varA ={name:Meatballs, fn:function() {Console.log ( This. Name); }    }    varb =A.fn; B.bind (a)//not be printed    varc =B.bind (a) Console.log (c); //function () {        //Console.log (this.name);    //}c ();//Meatballs

2, if the first parameter of call and apply is NULL, then this point is the Window object;

    varA ={name:Meatballs, fn:function() {Console.log ( This); //Window {external:object, Chrome:object, Document:document, A:object, speechsynthesis:speechsynthesis ...}        }    }    varb =A.fn; B ()//This points to the Window objectB.call (NULL);//This points to the Window objectB.apply (NULL);//This points to the Window objectB.bind (NULL)//not be printed

3, Parameters;

(1), call and apply can have multiple parameters, the difference is that the second parameter must be an array ;

 var  a = {name:  "Meatballs"  function   (m,n) {            Console.log ( this  .name);        Console.log (M  +n);    }}  var  b = A.fn; B.call (A,  6,6 //  meatball  //    b.apply (a,[ 6,4]);  //  meatballs     

(2), the same bind can have more than one parameter, and the parameters can be executed again when added, but note that the parameters are in the order of the formal parameter.

    varA ={name:Meatballs, fn:function(m,n) {Console.log ( This. Name); Console.log (M+N); }    }    varb =A.fn; B.bind (a)//not be printed    varc = B.bind (a,2) Console.log (c); //function (m,n) {        //Console.log (this.name);        //Console.log (m+n);    //}C (3); //Meatballs    //5

The similarities and differences between

call (), apply (), and bind ()

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.