This article mainly introduces how to deeply parse the use of the this keyword in JavaScript programming. It is the basic knowledge in JS learning. If you need it, you can refer to what this in JavaScript actually means? Many people will tell you that this refers to the current object. Is that true? In most cases, it is true. For example, we often write such JavaScript on the webpage:
Here this clearly refers to the current object, that is, the submit button. Generally, we use this in a similar way. But what is not the case?
Let's take a look at this example:
var foo = function() { console.log(this);}foo();new foo();
Comparing the running results of foo () and new foo (), you will find that the former this points to not foo itself, but the window object of the current page, the latter actually points to foo. Why?
In fact, this involves an important feature of JavaScript, the so-called "closure ". The concept of closure is not complicated, but it is not easy to say in one or two sentences. I will discuss the most important feature of Javascript in future articles. Now, I want to tell you that the scope in JavaScript becomes very important because of the existence of closures.
The so-called scope is simply the environment in which a function is created. The value of this variable, if not specified, is the current scope of the function.
In the previous example, the foo () function is in the global scope (here the window object), so the value of this is the current window object. In the form of new foo (), a copy of foo () is created and operated on the copy. Therefore, this is foo ().
This may be a bit abstract. Let's take a look at the actual example: