This keyword is very powerful in javascript, but it is difficult to use it if you don't know how it works.
The code copy is as follows:
function dosomething(){ this.style.color="#fff"; }
What does this point to in the above code? What will run dosomething() output?
In javascript, this always points to the currently executed function, or uses the function as the object called as the method. When we define the dosomething() method on the page, the owner of this is the current page, or the global object.
So when we execute the dosomething() function, it will raise an error. Because this function points to the global object window, and the window object does not have a style attribute.
copy:
The code copy 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 the HTML element, and the color of the corresponding HTML element will change. Every time dosomething is copied to the event, this points to the html element that currently executes this method.
Quote:
The code copy is as follows:
<element onclick="dosomething()">
At this time, you did not copy this method, but referenced this method. The onclick attribute does not contain the actual method, it is just a call to the method. When we execute this method, this points to the global window object again and raises an error.
The above is the entire content of this article. If you need it, please study it carefully.