Home >Web Front-end >JS Tutorial >What are the methods to change this pointer in js?

What are the methods to change this pointer in js?

下次还敢
下次还敢Original
2024-05-06 13:57:17855browse

In JavaScript, you can use the following methods to change this pointer: Bind: Returns a new function whose this value is bound to the specified object. Call and Apply: Call the function directly and allow specifying this value. Arrow functions: Implicitly bind this to its parent scope.

What are the methods to change this pointer in js?

In JavaScript, change the method pointed to by this

In JavaScript, The this keyword refers to the current object of the current execution context. However, sometimes it is necessary to change the pointer of this so that the same method can be used in different object contexts. The following are several ways to change the this pointer in JavaScript:

1. Bind

bind() Method returns a new function whose this value is bound to the specified object. The syntax is as follows:

<code>function.bind(object)</code>

For example:

<code>const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const boundGreet = person.greet.bind({ name: 'Mary' });
boundGreet(); // 输出:"Hello, my name is Mary"</code>

2. Call and Apply

call()## The # and apply() methods directly call a function and allow you to specify a this value. The syntax is as follows:

<code>function.call(object, arg1, arg2, ...)
function.apply(object, [arg1, arg2, ...])</code>
Unlike

bind(), call() and apply() will execute the function immediately.

For example:

<code>const person = {
  name: 'John'
};

function greet(greeting) {
  console.log(`${greeting}, my name is ${this.name}`);
}

greet.call(person, 'Hello'); // 输出:"Hello, my name is John"
greet.apply(person, ['Hello']); // 输出:"Hello, my name is John"</code>

3. Arrow function

Arrow function (

=>) is implicitly boundthis to its parent scope. This means that the this value inside an arrow function always points to the object that created it.

For example:

<code>const person = {
  name: 'John',
  greet: () => {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.greet(); // 输出:"Hello, my name is John"</code>

The above is the detailed content of What are the methods to change this pointer in js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn