This keyword is very powerful in JavaScript, but it is difficult to use it if you don't know how it works.
What does this in the above code point to, and what will be output when running dosomething()?
In JavaScript, this always points to the function currently executed, or the object that calls the function as a method. When we define the dosomething() method on the page, the owner of this is the current page, or It is said to be a global object.
So when we execute the dosomething() function, an error will occur. Because this of the function points to the global object window, and the window object does not have a style attribute.
Copy:
dosomething() is now copied entirely to the onclick attribute as a method. So if this event is executed, this will point to the HTML element, and the color of the corresponding HTML element will change. Each time dosomething is copied to the event, this It will point to the html element currently executing this method.
Quote:
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 an error is raised. .
The above is the entire content of this article. Friends in need should study it carefully.