This article mainly introduces the application example of this in javascript in the event, which is very helpful for our understanding of this keyword. we recommend it to you here. This keyword is very powerful in javascript, but it is difficult to use it if you don't know how it works.
The code is as follows:
Function dosomething () {this. style. color = "# fff ";}
In the above code, what does this point to? what does dosomething () output?
In javascript, this always points to the currently executed function, or uses the function as the object called by the method. after the dosomething () method is defined on the page, the owner of this is the current page or global object.
Therefore, executing the dosomething () function will cause an error because this of the function points to the global object window, and the window object does not have the style attribute.
Copy:
The code is as follows:
Element. onclick = dosomething;
Dosomething () is now copied to the onclick attribute as a method. so if this event is executed, this points to this HTML element, and the color of the corresponding HTML element changes. every time dosomething is copied to the event, this will point to the html element currently executing this method.
Reference:
The code is as follows:
At this time, you did not copy this method, but referenced this method. the onclick attribute does not contain the actual method, but is just a method call. when we execute this method, this points to the global window object again and raises an error.
The above is all the content of this article. if you need it, please study it.