js / apply, call, bind the difference

call, apply, bind these three methods are in fact inherited from Function.prototype of belonging to an instance method .

1、apply

  Changing apply method call directed to this function and the function is executed, note that when the apply parameter passing an array of

  Example:

    function  fn1(a ){ console.log(this, a)}

    let obj = {'b': 11}

    fn1.apply(obj1, [22])  // {'b': 11} , 22

2、call

  Changing apply method call directed to this function and the function is executed, note that when using the call parameters passed in the form of a single

  Example:

    function  fn1(a ){ console.log(this, a)}

    let obj = {'b': 11}

    fn1.call(obj1, 22)  // {'b': 11} , 22

3、bind

  Changing apply method call directed to this function, the function is not executed newly generated, using the newly generated functions apply call or invalid, does not change the function of this new generation, transmission methods as parameters and call

  Example:

    function  f1(){return  this.a}

    There obj1 = {a: 11111};

    There obj2 = {a: 22222};

    were f2 = f1.bind (obj1)

    f2() // 11111

    console.log(f2.call(obj2))           // 11111

    console.log(f1.call(obj2))           // 22222

4, apply and call the little knowledge

  Array.prototype.slice.apply ($ ( 'div')) // objects can be converted into an array-like array

  Array.prototype.slice.call ($ ( 'div')) // objects can be converted into an array-like array

Guess you like

Origin www.cnblogs.com/cuishuangshuang/p/12632487.html