Talk about this in Javascript again, talk about javascriptthis

Source: Internet
Author: User

Talk about this in Javascript again, talk about javascriptthis

I have always had a similar feeling about this in Javascript. Today I suddenly feel very open, so I would like to record it.

Let's first look at a chestnut:

<! DOCTYPE html> 

It seems that this code is correct, but the incorrect result is eventually caused by an incorrect understanding of this. We bound the click event on the element car_key, and thought that the dom element can access the car's this context by nesting the click event in the car class. This method looks reasonable, but unfortunately it doesn't work.

In Javascript, this keyword always points to the owner of the execution scope.

Please read the above sentence carefully. As we know, function calls will generate a new scope. When an onclick event is triggered, this points to the dom element rather than the Car class.

So how can we make it work? We usually assign this value to a local free variable (for example, that, _ this, self, me, etc., which is embodied in many frameworks) to avoid problems caused by the scope. Here we use local variables to override the previous method:

<! DOCTYPE html> 

Because that is a free variable, The onclick event does not cause its redefinition.

If you are familiar with ES6, you can use the fat arrow symbol, which is more concise and easier to understand, as shown below:

<! DOCTYPE html> 

Of course, we can also use the function binding method to solve this problem:

<! DOCTYPE html> 

In fact, these pitfalls encountered when learning React and binding events. At that time, I only knew this and did not know what was going on. Today, I suddenly felt very open. Hope to help you.

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.