Home > Web Front-end > JS Tutorial > body text

This in JS triggers bug analysis

小云云
Release: 2017-12-13 09:22:09
Original
1258 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template