Use call(), apply(), and bind() functions to change the this point of the function

In JavaScript, you can use  call(), apply() and  bind() functions to change  this the pointer of a function.

1. Using  call() functions

call() Functions can pass an object as the first argument to a function, set this object as  this the value of the function, and then execute the function. Its syntax is:

function.call(thisArg, arg1, arg2, ...)
  • thisArg is  this the object to set as the function value.
  • arg1, arg2, ... is the list of arguments passed to the function.

For example, the following code shows how to use  call() a function to change the value of a function  this :

const person1 = { name: 'John' };
const person2 = { name: 'Jane' };

function greeting() {
  console.log(`Hello, I'm ${this.name}`);
}

greeting.call(person1); // 输出:Hello, I'm John
greeting.call(person2); // 输出:Hello, I'm Jane

2. Using  apply() functions

apply() A function  call() works the same as a function, but the parameter list is passed to the function in the form of an array, and its syntax is:

function.apply(thisArg, [argsArray])
  • thisArg is  this the object to set as the function value.
  • argsArray is the list of parameters passed to the function, represented as an array.

For example, the following code shows how to use  apply() a function to change the value of a function  this :

const person1 = { name: 'John' };
const person2 = { name: 'Jane' };

function greeting(age) {
  console.log(`Hello, I'm ${this.name} and I'm ${age} years old`);
}

greeting.apply(person1, [30]); // 输出: Hello, I'm John and I'm 30 years old
greeting.apply(person2, [25]); // 输出: Hello, I'm Jane and I'm 25 years old

3. Using  bind() functions

bind() The function creates a new function instance and  this binds its value to the specified object. Instead of executing the function immediately like  call() and  apply() , it returns a  this new function bound to the specified value. Its syntax is:

function.bind(thisArg[, arg1[, arg2[, ...]]])
  • thisArg is  this the object to set as the function value.
  • arg1, arg2, ... is the list of arguments passed to the function.

For example, the following code shows how to use  bind() a function to change the value of a function  this :

const person1 = { name: 'John' };
const person2 = { name: 'Jane' };

function greeting(age) {
  console.log(`Hello, I'm ${this.name} and I'm ${age} years old`);
}

const greetingPerson1 = greeting.bind(person1);
greetingPerson1(30); // 输出: Hello, I'm John and I'm 30 years old

const greetingPerson2 = greeting.bind(person2);
greetingPerson2(25); // 输出: Hello, I'm Jane and I'm 25 years old

The above three ways can change  this the value of the function, but they have different purposes and implementation details.

Guess you like

Origin blog.csdn.net/m0_72446057/article/details/129612272