JavaScript You Don't Know - "this" (2)

   

What does this in JavaScript mean? Many people will tell you that this refers to the current object. Is this correct? True in most cases. For example, we often write JavaScript like this on web pages:

 

< input  type = "submit"  value = = "submit"  onclick = "this.value = 'submitting data'" /> 

 

Here this obviously refers to the current object, which is the submit button. Usually, we use this in similar situations. But what's not the case?

Let's look at this example:

 

var foo =function()   {
    console.log(
this
);
}

foo();
new foo();

 

Comparing the results of foo() and new foo(), you will find that the former does not point to foo itself, but the window object of the current page, while the latter actually points to foo. Why is this?

In fact, this involves an important feature of JavaScript, the so-called " closure ". The concept of closure is complicated and not complicated, but it is not so simple that it can be explained in one or two sentences. Occasionally, I will delve into this most important feature of Javascript in future articles. Now, what I'm going to tell you is that because of the existence of closures, scope in JavaScript has become quite important.

The so-called scope , simply put, is 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 (in this case the window object), so the value of this is the current window object. In the form of new foo(), a copy of foo() is actually created and the operation is performed on this copy, so this here is the copy of foo().

 

This may be a bit abstract, let's look at a practical example:

 

<input type="button" id="aButton" value="demo" onclick="" /> <script type="text/javascript">function demo() {this.value = Math.random();}</script>


    


 

If the demo() function is called directly, the program will report an error, because the demo function is defined in the window object, so the owner (scope) of the demo is window, and the this of the demo is also window. The window does not have a value attribute, so an error is reported.

diagram

If we add a copy of this function to an HTML element by creating a copy , then its owner becomes this element, and this also refers to this element:

 

document.getElementByIdx("aButton").onclick = demo;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325559812&siteId=291194637