SoFunction
Updated on 2025-04-14

JavaScript changes the four methods (bind, call, apply and arrow functions)

1. The basic concept of this

In JavaScript,thisis a special variable related to the execution context. Its value is usually determined based on how the function is called, rather than bound when the function is defined. understandthisThe behavior is the key to mastering the function execution mechanism in JavaScript.

1. This default pointer

In the global scope,thisDefault pointerwindow(In the browser environment). For example:

(this); // Output in the browser: Window

Inside the function,thisThe pointing depends on the call method. Usually, when calling a function directly,thisIt will point to the global object:

function showThis() {
  (this);
}

showThis(); // Output in the browser: Window

2. This in object method

When a function is called as an object's method,thisIt will point to this object:

const obj = {
  name: 'Object',
  showThis: function () {
    (this);
  }
};

(); // Output: obj object

2. Bind, call and apply methods

JavaScript provides three methods: bind, call and apply to manually set the pointing of this. These methods play a very important role in function execution.

1. bind() method

The bind() method returns a new function whose value of this new function will be permanently bound to the specified object. Commonly used when we need to ensure that this is pointing unchanged in event callbacks or asynchronous operations.

const obj = {
  name: 'Bound Object'
};

function showName() {
  ();
}

const boundShowName = (obj);
boundShowName(); // Output: 'Bound Object'

Use scenarios

bind()Frequently used in event handlers. For example, when a button click event occurs, we wantthisPoint to a specific object, not the default onewindow

const button = ('myButton');
('click', function() {
  const boundHandler = (this);
});

2. Call() method

call()Methods are used to call functions immediately and specify the internal functionthis. andbind()different,call()Execute the function directly and will not return a new function.

const obj = {
  name: 'Call Object'
};

function showName() {
  ();
}

(obj); // Output: 'Call Object'

Pass parameters

call()An important feature of  is that except for the first parameter, all subsequent parameters will be passed to the called function in turn. For example:

function greet(greeting, punctuation) {
  (greeting + ', ' +  + punctuation);
}

(obj, 'Hello', '!'); // Output: 'Hello, Call Object!'

3. Apply() method

apply()andcall()Similar, but its difference is thatapply()Accept an array of parameters instead of listing them one by one.

const obj = {
  name: 'Apply Object'
};

function showNameWithAge(age) {
  (`${}, Age: ${age}`);
}

(obj, [30]); // Output: 'Apply Object, Age: 30'

Passing parameter array

apply()Methods are very suitable for use when we have a set of parameters that need to be passed to a function:

const numbers = [5, 6, 2, 3, 7];
const max = (null, numbers);
(max); // Output: 7

3. This in the arrow function

The arrow functionthisUnlike traditional functions, it is not boundthis, but inherits from the context. This means that inside the arrow function,thisThe value of  is consistent with the context when defining the arrow function.

1. Arrow function this inherits features

In normal functions,thisThe pointer of   depends on the call method, and in the arrow function,thisAlways keep as defined asthissame:

const obj = {
  name: 'Arrow Object',
  showThis: () => {
    (this);
  }
};

(); // Output: Window (arrow function inherits the global `this`)

In this example,showThisis an arrow function that inherits the global context at the time of definition, sothisPoint to global objectwindow

2. Common application scenarios of arrow functions

Arrow functions are very useful when handling callback functions because it doesn't need to worry aboutthisThe direction of   will change. For example, in an event handler, we can use arrow functions to ensure thatthisThe pointing remains unchanged:

const obj = {
  name: 'Event Object',
  handleClick: function () {
    setTimeout(() => {
      (); // Since the arrow function does not have its own `this`, it will inherit the `this` of the `handleClick` method    }, 1000);
  }
};

(); // Output in one second: 'Event Object'

4. Summary and best practices

1. When to usebind()call()andapply()

  • bind(): When you need to call the function at some point in the future, and make surethisWhen pointing to  , usebind(). Especially in event processing or timer,bind()Very useful.
  • call(): If you need to call the function immediately and you can explicitly pass multiple parameters, usecall()
  • apply(): When the parameter of a function exists in an array, useapply(). It makes the code more concise and flexible.

2. Best practices for arrow functions

  • Inheritancethis: When you need to keep in nested functionsthisWhen pointing, the arrow function is a concise way without explicit bindingthis
  • Avoid abuse: Although the arrow function is concise, itsthisInheritance features can cause problems in some scenarios, especially in object-oriented programming, avoiding the abuse of arrow functions as object methods.

The above is the detailed content of the four methods (bind, call, apply and arrow functions) in JavaScript to change this pointing (bind, call, apply and arrow functions). For more information about JavaScript changing this pointing, please follow my other related articles!