简单的解说如何使用 call, apply, bind

简单的解说如何使用 call, apply, bind.


function func(y,z){
  
  console.log(this.x,y,z);
  
}

var obj = {x:1};


//Use Call:
//(It executes right away)
//Output 1, undefined, undefined

func.call(obj);


//Use Apply:
//(Same as call, but add one more argument of Array for the function's parameters)
//Output 1, 2, 3

func.apply(obj,[2,3]);


//Use bind:
//(bind it as a new function, and execute in the future function call)

var boundFunc = func.bind(obj);
boundFunc();//Output 1, undefined, undefined