[Similarities]

Prototye are all native methods (function.prototye), and all functions can call on these three methods to change the this pointer

[the difference]

  • Call pass-hashing (one by one)
  • Apply pass parameters – package (put all parameters in an array)
  • Bind passes arguments – same as call

call

  • fn.call(context,para1,para2….)
  • Execute the fn method, and make this in the fn method context, and para1… Are arguments passed to fn
//=> Non-strict mode
function fn(num1,num2){
    console.log(this);
}
var obj={fn:fn};
obj.fn(); //this:obj

var opp={};
//opp.fn(); // Error: no fn attribute in opp
fn.call(opp); //this:opp num1,num2 are undefined
fn.call(1.2); //this:1 num1=2 num2=undefined
fn.call(opp,1.2); //this:opp num=1,num2=2

//=> Call is special
fn.call(); //this: window
fn.call(null);//this:window
fn.call(undefined); //this:window
Copy the code
//=> Strict mode
"use strict"
fn.call(); //this:undefined
fn.call(undefined); //this:undefined
fn.call(null); //this:null
Copy the code

apply

The syntax of apply is basically the same as that of call, and the principle of operation is basically the same. The only difference is that apply stores arguments passed to functions as arrays (but it is equivalent to passing argument values to functions one by one).

fn.call(null.10.20.30);
fn.apply(null[10.20.30])
Copy the code

Bind (preprocessing mechanism)

  • It is not compatible under IE6-8; It doesn’t work the same way that Call (and apply) change this
  • Pass all arguments to the method in front of the dot, and return a small function that receives the arguments (the return value is the function definition).
  • Preprocessing mechanism: Everything is taken care of in advance, and the final function execution needs to be run manually
function fn(n,m){
    console.log(this+n+m)
}
var res = fn.bind({},3.5)
res(); //[object Object]35
Copy the code

Supplement:

  • Call inheritance: Only the private methods of the parent class are inherited
  • Use apply to find the maximum value in an array
let max = Math.max.apply(Math,ary),
    min = Math.min.apply(Math,ary);
console.log(max, min);
Copy the code