


What does this in js events represent? Detailed explanation of the usage of this in js (with usage examples)
This article will use examples to analyze the usage of this in js. The understanding of this in js is also explained in detail. From the following example, we can know: for obj.foo(), foo runs in obj environment, so this points to obj; for foo(), foo runs in the global environment, so this points to the global environment. Therefore, the operating results of the two are different. It can be seen that this plays a decisive role in it. I hope this article can give everyone a reference value.
1. The origin of the problem
One sign of learning JavaScript language is to understand the following two writing methods, which may have different results.
var obj = { foo: function () {} }; var foo = obj.foo; // 写法一 obj.foo() // 写法二 foo()Copy after login
In the above code, although obj.foo
and foo
point to the same function, the execution results may be different. Please see the example below.
var obj = { foo: function () { console.log(this.bar) }, bar: 1 }; var foo = obj.foo; var bar = 2; obj.foo() // 1 foo() // 2Copy after login
The reason for this difference lies in the use of the this
keyword inside the function body. Many textbooks will tell you that this
refers to the environment in which the function is run. For obj.foo()
, foo
runs in the obj
environment, so this
points to obj
; For foo()
, foo
runs in the global environment, so this
points to the global environment. Therefore, the operating results of the two are different.
This explanation is correct, but textbooks often don’t tell you why this is the case? In other words, how is the running environment of the function determined? For example, why obj.foo()
is executed in the obj
environment, and once var foo = obj.foo
, foo()
Will it be executed in the global environment?
This article will explain the principle of JavaScript processing. Once you understand this, you will fully understand the role of this
.
2. Memory data structure
The reason why JavaScript language has this
design is related to the data structure in memory.
var obj = { foo: 5 };Copy after login
The above code assigns an object to the variable obj
. The JavaScript engine will first generate an object { foo: 5 }
in the memory, and then assign the memory address of this object to the variable obj
.
In other words, the variable obj
is an address (reference). If obj.foo
is to be read later, the engine first gets the memory address from obj
, then reads the original object from the address and returns its foo
Attributes.
The original object is saved in a dictionary structure, and each attribute name corresponds to an attribute description object. For example, the foo
attribute in the above example is actually saved in the following form.
{ foo: { [[value]]: 5 [[writable]]: true [[enumerable]]: true [[configurable]]: true } }Copy after login
Note that the value of the foo
attribute is stored in the value
attribute of the attribute description object.
3. Function
This structure is very clear. The problem is that the value of the attribute may be a function.
var obj = { foo: function () {} };Copy after login
At this time, the engine will save the function separately in the memory, and then assign the address of the function to the value
of the foo
attribute Attributes.
{ foo: { [[value]]: 函数的地址 ... } }Copy after login
Since the function is a single value, it can be executed in different environments (contexts).
var f = function () {}; var obj = { f: f }; // 单独执行 f() // obj 环境执行 obj.f()Copy after login
4. Environment variables
JavaScript allows other variables of the current environment to be referenced within the function body.
var f = function () { console.log(x); };Copy after login
In the above code, the variable x
is used in the function body. This variable is provided by the runtime environment.
Now comes the problem. Since functions can be executed in different running environments, there needs to be a mechanism to obtain the current running environment (context) inside the function body. Therefore, this
appears. Its design purpose is to refer to the current running environment of the function inside the function body.
var f = function () { console.log(this.x); }Copy after login
In the above code, this.x
in the function body refers to x
of the current running environment.
var f = function () { console.log(this.x); } var x = 1; var obj = { f: f, x: 2, }; // 单独执行 f() // 1 // obj 环境执行 obj.f() // 2Copy after login
In the above code, function f
is executed in the global environment, and this.x
points to x
of the global environment.
is executed in the obj
environment, this.x
points to obj.x
.
Back to the question raised at the beginning of this article, obj.foo()
finds foo
through obj
, so it is in obj
environment execution. Once var foo = obj.foo
, the variable foo
points directly to the function itself, so foo()
becomes executed in the global environment.
Related recommendations:
The above is the detailed content of What does this in js events represent? Detailed explanation of the usage of this in js (with usage examples). 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











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

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

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 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

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:

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

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

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
