Home Web Front-end JS Tutorial This in JS triggers bug analysis

This in JS triggers bug analysis

Dec 13, 2017 am 09:22 AM
javascript this

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();
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles