How to modify the value of this in js, call, apply, bind

call, applyand bindare all methods used to explicitly modify thisthe value of a function. The differences between them are as follows:

  1. callmethod:
    • callThe method immediately calls the function, passing the specified object as the function's thisvalue.
    • callThe method accepts a list of parameters, which are passed to the function in turn.
    • If the function needs to pass multiple parameters, you can use commas to separate the parameters passed to callthe method.
    • callThe syntax of the method is:function.call(thisArg, arg1, arg2, ...)
function sayHello(greeting) {
    
    
  console.log(greeting + ', ' + this.name);
}

const obj = {
    
    
  name: 'Alice'
};

sayHello.call(obj, 'Hello'); // 输出:Hello, Alice
  1. applymethod:
    • applyThe method immediately calls the function, passing the specified object as the function's thisvalue.
    • applyThe method accepts two parameters: thisArgand a parameter array.
    • The elements in the parameter array are passed to the function in sequence.
    • If the function needs to pass multiple parameters, and these parameters already exist in the array, you can use applythe method.
    • applyThe syntax of the method is:function.apply(thisArg, [argsArray])
function sayHello(greeting) {
    
    
  console.log(greeting + ', ' + this.name);
}

const obj = {
    
    
  name: 'Alice'
};

sayHello.apply(obj, ['Hello']); // 输出:Hello, Alice
  1. bindmethod:
    • bindThe method creates a new function, binds the specified object to the function's thisvalue, and returns the new function.
    • The bound thisvalue does not immediately execute the function, but instead returns a new function that can be called when needed.
    • bindMethods can pass additional parameters as parameters to the bound function.
    • bindThe syntax of the method is:function.bind(thisArg, arg1, arg2, ...)
function sayHello() {
    
    
  console.log(this.name);
}

const obj = {
    
    
  name: 'Alice'
};

const boundFunc = sayHello.bind(obj);
boundFunc(); // 输出:Alice

Summarize:

  • callThe and applymethods are used to call a function immediately, passing the specified thisvalue and parameter list.
  • bindMethod is used to create a new function and thisbind the specified value to the function.
  • callMethods take a comma separated list of arguments, applymethods take an array of arguments, and bindmethods can pass arguments when creating a new function.
  • callThe and applymethods will execute the function immediately, while bindthe method returns a new function that needs to be called manually.
  • All of these methods allow the function's value to be modified explicitly thisso that the function executes correctly in a specific context. The method chosen depends on whether the function needs to be executed immediately and how the parameters are passed.

Guess you like

Origin blog.csdn.net/qq_41045651/article/details/131596397