Use of apply and call and bind in javascript

  • 2021-07-21 06:59:37
  • OfStack

fun.apply(context,[argsArray])

Immediately call fun, and point the original this of fun function to the new context object passed in, so that the same method can be reused on different objects.

context: The passed-in object that replaces the original this of the fun function;

argsArray: An array or class array object in which the array parameters are expanded and passed to the fun function as separate arguments, paying attention to the order of the parameters.

fun. call (context, [arg1], [arg2], […])

Unlike apply, only the parameter list is different, and the parameters of call need to be passed in one by one. If the number of parameters is not known, apply is used.

Use:

Math. max () takes only individual parameters, and you can use the max method on an array by:


Math.max.apply(null, array) ; // Will array Array parameters are expanded into separate parameters and then passed in 
Array.prototype.push.apply(arr1,arr2);// Will 1 Array disassembly push To another 1 In an array; No need apply Subsequent array parameters are treated as 1 Elements push Get in. 
Array.prototype.slice.call(arguments);// Use on a primitive group object slice Method 

fun. bind (context, [arg1], [arg2], […])

Make the context executed by the fun method unchanged.

arg1: List of arguments to pass to the new function

Returns a function for subsequent calls, the body of which is similar to the original function fun1, but the this of the new function points to the newly passed context object. The new function has the specified initial parameters, and the arguments should be arranged later when it is called later.


var displayArgs = function (val1, val2, val3, val4) {
 console.log(val1 + " " + val2 + " " + val3 + " " + val4);
}
var emptyObject = {};
//  When the new function is generated, the 2 Parameters 
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");
//  Pass in another when calling 2 Parameters, back row 
displayArgs2("b", "c");
// Output: 12 a b c

Override the slice () method with the bind () method:


var _Slice = Array.prototype.slice;
var slice = Function.prototype.call.bind(_Slice);
slice( … ); 

bind () compatible with Ie5 ~ ie8 processing


if (!Function.prototype.bind) {
 Function.prototype.bind = function(context) {
  var self = this, //  That is, calling bind Objective function of method 
  args = arguments;
  return function() {
   self.apply(context, Array.prototype.slice.call(args, 1));
  }
 }
}

1 In general, the this of setTimeout () points to an window or global object. You can use bind () to bind this to the calling object when you need this to point to the class instance when using the method of the class.


Related articles: