Home > Web Front-end > JS Tutorial > body text

A brief discussion on the application of this in events in javascript_javascript skills

WBOY
Release: 2016-05-16 16:13:57
Original
1132 people have browsed it

This keyword is very powerful in JavaScript, but it is difficult to use it if you don't know how it works.

Copy code The code is as follows:

function dosomething(){ this.style.color="#fff"; }

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:

Copy code The code is as follows:

element.onclick=dosomething;

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:

Copy code 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 an error is raised. .

The above is the entire content of this article. Friends in need should study it carefully.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template