Introduction to the application of this in the event in javascript _ javascript skills

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.