apply, call and bind [JS]

Keywords: Javascript

1. apply

1.1 use of apply

apply()   Method calls a function with a given value of this, and with an array (or Class array object )Parameters provided in the form of

Note: the function of the call() method is similar to that of the apply() method, except that the call() method accepts a parameter list, while the apply() method accepts an array of parameters.

const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);

console.log(max);
// expected output: 7

const min = Math.min.apply(null, numbers);

console.log(min);
// expected output: 2

apply   And   call()   Very similar, except in the way parameters are provided. apply   Use an array of parameters instead of a list of parameters. apply   You can use array literal, such as   Fun. Apply (this, ['eat ',' Banana ']), or array object,   as    fun.apply(this, new Array('eat', 'bananas')).

1.2 add array items to another array with apply

We can use push to append elements to the array. Since push accepts a variable number of parameters, you can also append multiple elements at a time.

However, if the push parameter is an array, it will add the array as a single element instead of adding each element in the array, so we will eventually get an array in the array. What if you don't want to? concat meets our needs, but instead of adding elements to an existing array, it creates and returns a new array. However, we need to append elements to the existing array, so we can use apply

var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

1.3 using apply and built-in functions

For some requirements that need to write a loop in order to calendar the array items, we can use apply to avoid the loop.

The following is an example. We will use Math.max/Math.min to find the maximum / minimum value in the array.

/* Find the largest / smallest number in the array */
var numbers = [5, 6, 2, 3, 7];

/* Code when using Math.min/Math.max and the apply function */
var max = Math.max.apply(null, numbers); /* Basically equivalent to Math.max(numbers[0],...) or Math.max(5, 6,...) */
var min = Math.min.apply(null, numbers);

/* Comparison: simple loop algorithm */
max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min)
    min = numbers[i];
}

2. call

2.1 call usage

In a child constructor, you can call the parent constructor   call   Method to implement inheritance, similar to   Java   Writing in. In the following example, use   Food   and   Toy   All object instances created by the constructor will have   Product   Added in constructor   name   Properties and   price   Property, but   category   Properties are defined in their respective constructors.

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

2.2 calling anonymous functions using call method

In the for loop in the following example, we create an anonymous function, and then execute the anonymous function by calling the call method of the function, taking each array element as the specified this value. The main purpose of this anonymous function is to add a print method to each array element object. This print method can print the correct index numbers of each element in the array. Of course, it is not necessary to let the array element pass in the anonymous function as the value of this (just ordinary parameters). The purpose is to demonstrate the usage of call.

var animals = [
  { species: 'Lion', name: 'King' },
  { species: 'Whale', name: 'Fail' }
];

for (var i = 0; i < animals.length; i++) {
  (function(i) {
    this.print = function() {
      console.log('#' + i + ' ' + this.species
                  + ': ' + this.name);
    }
    this.print();
  }).call(animals[i], i);
}

2.3 use the call method to call the function and specify the 'this' of the context

In the following example, when called   greet   Method, the this value of the method will be bound to   obj   Object.

function greet() {
  var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
  console.log(reply);
}

var obj = {
  animal: 'cats', sleepDuration: '12 and 16 hours'
};

greet.call(obj);  // cats typically sleep between 12 and 16 hours

2.4 use the call method to call the function without specifying the first argument

In the following example, we call   display   Method, but its first argument is not passed. If the first parameter is not passed, this   The value of will be bound as a global object.

var sData = 'Wisen';

function display() {
  console.log('sData value is %s ', this.sData);
}

display.call();  // sData value is Wisen

Note: in strict mode, this   The value of will be   undefined. See below.

'use strict';

var sData = 'Wisen';

function display() {
  console.log('sData value is %s ', this.sData);
}

display.call(); // Cannot read the property of 'sData' of undefined    

3. bind

The bind() method creates a new function. When bind() is called, this of the new function is specified as the first parameter of bind(), and the other parameters will be used as the parameters of the new function for calling.

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42

The bind() function creates a new binding function (binding function, BF). Binding function is a strange function object (strange function object, a term in ECMAScript 2015), which wraps the original function object. Calling a bound function usually results in the execution of a wrapper function.

The binding function has the following internal properties:

  • [[BoundTargetFunction] - wrapped function object
  • [[BoundThis]] - the value always passed as this value when calling the wrapper function.
  • [[BoundArguments] - list. When making any call to the wrapper function, the parameter list will be filled with list elements first.
  • [[Call]] - execute the code associated with this object. Called through a function Call expression. The arguments to the internal method are a value of this and a list containing the arguments passed to the function through the Call expression.

When calling the binding function, it calls the internal method [[Call]] on [[BoundTargetFunction]], like Call(boundThis, args). Where BoundThis is [[BoundThis]], args is [[BoundArguments]] plus the parameter list passed in through the function Call.

Binding functions can also be used new Operator construction, which will appear as if the objective function has been constructed. The supplied value of this will be ignored, but the pre parameter will still be supplied to the analog function.

Posted by hrichman on Tue, 28 Sep 2021 01:33:25 -0700