Home  >  Article  >  Web Front-end  >  Detailed interpretation of the bug caused by this in JS

Detailed interpretation of the bug caused by this in JS

亚连
亚连Original
2018-06-21 14:20:271277browse

This article mainly introduces the analysis of bugs caused by this in JavaScript and the analysis of related processing methods. Let's study together.

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. Here is what we have compiled for you Related content:

In JavaScript, there is a very special, very commonly used thing 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 anything in the global object (window) Attributes, we can use it directly without using ".".

The result will be 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 in the object If the value 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 is a function, We will call this newly created thing "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.

A reference to this in JavaScript bug

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, it can be imagined that when I execute this method, it will change the value of c.name.

There is no big problem with this part, but let us 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 come back and take a look at our window object. We will find that a new attribute "name" was 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!

In the setname function, use console.log(this) to take a look:

In the log In this 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 second one in setname This points 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 like 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 will Points 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 we encounter situations 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();

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to use vue-cli to implement multi-page applications

How to implement the array update function in VUE

Using modular development in vuejs

What should we pay attention to when optimizing Vue projects?

How to implement component communication in vue-cli

The above is the detailed content of Detailed interpretation of the bug caused by this in JS. 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