Elaborate call, apply and bind the difference and usage

call and apply common

They have in common is that both can be changed when the function execution context, a method of one object to another object to perform, and are executed immediately.

Why change the execution context? For a small example of life: usually do not have time to cook, I want to give children the weekend a stew pickled Benedict fresh taste. But no suitable pot, and I do not come up to buy. So I asked a neighbor to borrow a pot with, then it will achieve the purpose, but also saves money, do both.

Changing the execution context is the same, there is a method objects A and B objects for some reason, also need to use the same method, so this time we are alone expand it a way to target B, A or borrow object methods it? A subject of course to borrow friends, both completed the requirements, and reduced memory usage.

In addition, they are also very similar wording, calling call and apply object must be a function Function. Next, there will be when it comes to specific wording, it is mainly their differences.

The difference between the call and apply

Their difference is mainly reflected in the wording of the parameter. First look at their own specific wording.

call wording

Function.call(obj,[param1[,param2[,…[,paramN]]]])

Note the following:

  • Call call the object, it must be a function Function.
  • The first argument to call, an object. Function of the caller, will point to the object. If you do not pass, it will default to the global object window.
  • The second parameter starts, can receive any number of parameters. Each parameter is mapped to a corresponding location parameter Function. However, if all of the parameters passed as an array, as a whole they will be mapped to the corresponding first parameter Function, after the arguments are empty.
function FUNC (A, B, C)} { 

func.call (obj, l, 2,3 )
 // FUNC actually received parameter l, 2,3 

func.call (obj, [ l, 2,3 ])
 // FUNC actually received parameter [1,2,3], undefined, undefined

apply in writing

Function.apply(obj[,argArray])

have to be aware of is:

  • It must be a function call Function, and receives only two parameters, the first parameter of rules consistent with the call.
  • The second parameter must be an array or array type, they are converted into an array type, the incoming Function, and is mapped to the corresponding parameters Function. , A very important difference between this call and also apply.
func.apply (obj, [l, 2,3 ])
 // FUNC actually received parameter l, 2,3 

func.apply (obj, {
     0:. 1 ,
     . 1: 2 ,
     2:. 3 , 
    length: . 3 
}) 
// FUNC actually received parameter 1,2,3

call and apply use

List the call and apply some usage scenarios, respectively. Disclaimer: No example is the scene must call or must apply, but with it so personal habits.

call usage scenarios

1, inherited objects. As in the following example:

function superClass () {
    this.a = 1;
    this.print = function () {
        console.log(this.a);
    }
}

function subClass () {
    superClass.call(this);
    this.print();
}

subClass();
// 1

subClass by call method, inherited superClass the print method and a variable. In addition, subClass can also expand their other methods.

2, borrowing methods. Remember array of classes just what? If you want to use it on the Array prototype chain, it can be:

let domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

In this way, domNodes on all methods under the Array can be applied.

apply some of the magical effect

1, Math.max. Use it to get an array of the largest one.

let max = Math.max.apply(null, array);

2, two arrays to achieve the merger. Before ES6 expansion operators appear, we can use Array.prototype.push to achieve.

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

Array.prototype.push.apply(arr1, arr2);
console.log(arr1); // [1, 2, 3, 4, 5, 6]

bind use

Finally, he said bind. Explanation on the MDN is: bind () method creates a new function, set this keyword when you call to the value provided. And when calling a new function, given as a list of parameters before several parameters sequence of the original function.

Its syntax is as follows:

Function.bind(thisArg[, arg1[, arg2[, ...]]])

bind method similar to apply and call comparison, this can also change the point of the body of the function. The difference is that the return value is a function of the bind method, and the need to call later, will be performed. The call is a call and apply immediately.

Consider the following example:

function the Add (A, B) {
     return A + B; 
} 

function Sub (A, B) {
     return A - B; 
} 

add.bind (Sub, . 5,. 3); // this time, and does not return. 8 
the Add .bind (Sub,. 5,. 3) (); // after the call, returns 8

If the first parameter bind is null or undefined, this points to the global object window.

Realization bind:

function bind(thisArg) {
    // Does not work with `new funcA.bind(thisArg, args)`
    if (!Function.prototype.bind) (function(){
      var slice = Array.prototype.slice;
      Function.prototype.bind = function() {
        var thatFunc = this, thatArg = arguments[0];
        var args = slice.call(arguments, 1);
        if (typeof thatFunc !== 'function') {
          // closest thing possible to the ECMAScript 5
          // internal IsCallable function
          throw new TypeError('Function.prototype.bind - ' +
                 'what is trying to be bound is not callable');
        }
        return function(){
          var funcArgs = args.concat(slice.call(arguments))
          return thatFunc.apply(thatArg, funcArgs);
        };
      };
    })();
}

 

Guess you like

Origin www.cnblogs.com/momo798/p/11944375.html