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 ()