Several ways to handle 'this' pointer in JS
I like to change the pointer of the function execution context in JS, also known as the this
pointer.
For example, we can use array methods on array-like objects:
const reduce = Array.prototype.reduce; function sumArgs() { return reduce.call(arguments, (sum, value) => { return sum += value; }); } sumArgs(1, 2, 3); // => 6
On the other hand, this
is difficult to grasp.
We often find that the this
we use is incorrect. The following teaches you how to simply bind this
to the desired value.
Before I begin, I need a helper function execute(func)
that simply executes the function provided as an argument.
function execute(func) { return func(); } execute(function() { return 10 }); // => 10
Now, moving on to understanding the essence of the error surrounding this
: method separation.
1. Method separation problem
Suppose there is a class Person
containing fields firstName
and lastName
. Additionally, it has a method getFullName()
, which returns the full name of the person. As shown below:
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.getFullName = function() { this === agent; // => true return `${this.firstName} ${this.lastName}`; } } const agent = new Person('前端', '小智'); agent.getFullName(); // => '前端 小智'
You can see that the Person
function is called as a constructor: new Person('front-end', 'Xiao Zhi')
. this
inside the function represents the newly created instance.
getfullname()
Returns the person's full name: 'Front-end Xiaozhi'
. As expected, this
inside the getFullName()
method is equal to agent
.
What happens if the auxiliary function executes the agent.getFullName
method:
execute(agent.getFullName); // => 'undefined undefined'
The execution result is incorrect: 'undefined undefined'
, this isthis
Problem caused by incorrect pointing.
Now in the getFullName()
method, the value of this
is the global object (window
in the browser environment). this
is equal to window
, ${window.firstName} ${window.lastName}
The execution result is 'undefined undefined'
.
This happens because the method is detached from the object when execute(agent.getFullName)
is called. Basically what happens is just a regular function call (not a method call):
execute(agent.getFullName); // => 'undefined undefined' // 等价于: const getFullNameSeparated = agent.getFullName; execute(getFullNameSeparated); // => 'undefined undefined'
This is what is called when a method is detached from its object. When a method is detached and then executed, this
There is no connection to the original object.
In order to ensure that this
inside the method points to the correct object, this must be done
Execute the method as a property accessor:
agent.getFullName()
-
Or statically bind
this
to the containing object (using arrow functions,.bind()
method, etc.)
method separation problem , and the resulting incorrect pointing of this
will generally occur in the following situations:
Callback
// `methodHandler()`中的`this`是全局对象 setTimeout(object.handlerMethod, 1000);
When setting up an event handler,
// React: `methodHandler()`中的`this`是全局对象 <button onClick={object.handlerMethod}> Click me </button>
then introduces some useful methods, that is, how to make this
point to the desired object if the method is detached from the object.
2. Close the context
The easiest way to keep this
pointing to the class instance is to use an additional variable self
:
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; const self = this; this.getFullName = function() { self === agent; // => true return `${self.firstName} ${self.lastName}`; } } const agent = new Person('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
getFullName()
statically closes the self
variable, effectively manually binding this
.
Now when calling execute(agent.getFullName)
everything works fine because getFullName()
inside the method this
always points to correct value.
3. Using arrow functions
Is there a way to statically bind this
without additional variables? Yes, that's exactly what arrow functions do.
Refactoring using arrow functions Person
:
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.getFullName = () => `${this.firstName} ${this.lastName}`; } const agent = new Person('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
Arrow functions lexically bind this
. Simply put, it uses the value from the external function this
it is defined in.
It is recommended to use arrow functions in all cases where an external function context is required.
4. Binding context
Now let’s go one step further and use the class refactoring Person
in ES6.
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } getFullName() { return `${this.firstName} ${this.lastName}`; } } const agent = new Person('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => 'undefined undefined'
Unfortunately, even with the new class syntax, execute(agent.getFullName)
still returns "undefined undefined"
.
In the case of a class, using an additional variable self
or an arrow function to fix what this
points to won't work.
But there is a trick involving the bind()
method, which binds the context of the method into the constructor:
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.getFullName = this.getFullName.bind(this); } getFullName() { return `${this.firstName} ${this.lastName}`; } } const agent = new Person('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
this in the constructor .getFullName = this.getFullName.bind(this)
Bind the method getFullName()
to the class instance.
execute(agent.getFullName)
Works as expected, returning 'frontend Xiaozhi'
.
5. Fat arrow method
#bind
The method is a bit too lengthy, we can use the fat arrow method:
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } getFullName = () => { return `${this.firstName} ${this.lastName}`; } } const agent = new Person('前端', '小智'); agent.getFullName(); // => '前端 小智' execute(agent.getFullName); // => '前端 小智'
胖箭头方法getFullName =() =>{…}
绑定到类实例,即使将方法与其对象分离。
这种方法是在类中绑定this
的最有效和最简洁的方法。
6. 总结
与对象分离的方法会产生 this 指向不正确问题。静态地绑定this
,可以手动使用一个附加变量self
来保存正确的上下文对象。然而,更好的替代方法是使用箭头函数,其本质上是为了在词法上绑定this
。
在类中,可以使用bind()
方法手动绑定构造函数中的类方法。当然如果你不用使用 bind
这种冗长方式,也可以使用简洁方便的胖箭头表示方法。
更多JavaScript知识请关注PHP中文网JavaScript视频教程栏目
The above is the detailed content of Several ways to handle 'this' pointer in JS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
