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.
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>
bind(),
call() and
apply() will execute the function immediately.
<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 bound
this to its parent scope. This means that the
this value inside an arrow function always points to the object that created it.
<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!