search
HomeWeb Front-endJS TutorialThis in JS triggers bug analysis

This in JS triggers bug analysis

Dec 13, 2017 am 09:22 AM
javascriptthis

In js, the context of this is always unpredictable. Many times when bugs occur, you are always confused. In fact, you only need to understand how to execute it in different situations. This article mainly introduces the analysis of this trigger in JavaScript. Analysis of bugs and related processing methods, I hope it can help everyone.

There is a very special and commonly used thing in JavaScript that often troubles beginners - "this". In this class, we will talk about this "this".

This usually points to an object, and this will point to different objects in different situations. Let's look at a few different scenarios to help us understand "this" better.

window object (global object)

Here we print "this" in three different situations, namely executing it directly in the outermost environment of the function; using fuction statement To execute; use function expression to execute (if you are still unclear about the difference between function statement and function expression, you can refer to Note 1).


As a result, you will find that these three "this" will point to the same object, which is the window object (global object) of the global environment:


That is to say, we can directly use this function and this to create new properties in the window object:

Here we use this. NewVariable = "..." to create new properties in the window object. At the end of the function, we can directly console.log(NewVariable). The reason why there is no need to type this.NewVariable or window.NewVariable here is because any In the properties of global object (window), we can use it directly without using ".".


The result will look like this:


It will print out our "Create a new property", at the same time, in the large object window, we will also find the NewVariable attribute:


method in object

We know that if the value in the object is a primitive type (for example, string, numerical value, logical value), we will call the newly created thing "property"; if the value in the object If the value is a function, we will call the newly created thing a "method".

Here, we are going to establish the method:

First, we use object literal to create an object c, which contains the attribute name and method log. Log is an anonymous function. The function content is very simple, just printing this (refer to Note 1 for anonymous functions). Finally, use c.log to execute this method.


#Let’s take a look, what will “this” be at this time?

The answer is object c!

When this function is a method in an object, this will point to the object containing this method


About in JavaScript A bug of this

Let us extend this example further:

Suppose we add this line in the method logthis.name = "Updated Object C name"


Because we know that "this" now refers to object c, so as you can imagine, when I execute this method, it will change c The value of .name.


There is no big problem with this part, but let’s continue reading….

Suppose I am making some changes in the method log. In this method, I create another function called setname. I also use the method this.name = newname to modify this object. The value of the name attribute in c.

Then execute the setname function, hoping to change the attribute value of name in object c to "New name for object c", and finally print "this" to take a look.


As a result, we will find that the value of the name attribute in object c has not changed to "New name for object c", it is still the same! ? How did that happen?


Look carefully, let's go back and take a look at our window object. We will find that a new attribute "name" is found in the window object, and The value is "New name for object c".


What does it mean? It means that the this we just pointed to in the function setname points to the global object (window object), not the object C just now!


Let’s use console.log(this) to take a look at the setname function:


In the log method, we executed console.log(this) three times in total and the results are as follows:

The first and third "this" point to object c, and the third The two this in setname point to the window object (global object), and this is why the setname function cannot help us modify the name of the name attribute in object c, because "this" does not point to object c at all. .


#And many people think that this is a bug in JavaScript.

So what can we do

So when we encounter the above example, what can we do to avoid pointing to different objects?

Many people’s solution is this, because we know that objects are all referenced, so we can do this

STEP 1

We do this in the entire function Add the line var self = this at the top (some people will use var that = this). Due to the characteristics of references, self and this will point to the same object, and this points to object c, so self will also point to object c.

STEP 2

Next, change the "this" originally used in the method log to "self". This can ensure that self points to the c object without worrying about the above The example also points to the wrong object.


The result is as we expected. When console.log(self) is used for the second time, the value of the name attribute in object c is replaced again.


Summary

Let us summarize:

If we create a function in the global environment and print this, this At this time, this will point to the global object, which is the window object.

If we create a function in an object, that is, a method, this will generally point to the object containing the method (the reason why we say "generally" is because in addition to the above Except in the case of bugs).

When encountering a situation where we don’t know what this points to in the method, in order to avoid unnecessary errors, we can create a variable at the top of the method and specify it as this (var self = this).

4. If you really still don’t know what this will point to in that situation, just console.log and take a look!

Sample code


// function statement
function a(){
 console.log(this);
 this.NewVariable = "Create a new property";
}
a();
console.log(NewVariable);
var c = {
 name:"The C object",
 log: function(){
 var self = this;
 self.name = "Updated object C name";
 console.log(self);
 
 var setname = function(newname){
  self.name = newname;
  console.log(self);
 }
 setname("New name for object c");
 console.log(self)
 }
}
c.log();

After reading this article, I believe everyone is aware of the bug caused by this in JS. If you need it, quickly collect it. .

Related recommendations:

Understanding of this in js

Detailed explanation of the difference between this and event in JS

Usage example analysis of this in js_javascript skills

The above is the detailed content of This in JS triggers bug analysis. 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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor