Deep understanding of this keyword in JavaScript programming

Source: Internet
Author: User
This article mainly introduces how to deeply parse the use of the this keyword in JavaScript programming. It is the basic knowledge in JS learning. If you need it, you can refer to what this in JavaScript actually means? Many people will tell you that this refers to the current object. Is that true? In most cases, it is true. For example, we often write such JavaScript on the webpage:

 

Here this clearly refers to the current object, that is, the submit button. Generally, we use this in a similar way. But what is not the case?

Let's take a look at this example:

var foo = function() {  console.log(this);}foo();new foo();

Comparing the running results of foo () and new foo (), you will find that the former this points to not foo itself, but the window object of the current page, the latter actually points to foo. Why?

In fact, this involves an important feature of JavaScript, the so-called "closure ". The concept of closure is not complicated, but it is not easy to say in one or two sentences. I will discuss the most important feature of Javascript in future articles. Now, I want to tell you that the scope in JavaScript becomes very important because of the existence of closures.

The so-called scope is simply the environment in which a function is created. The value of this variable, if not specified, is the current scope of the function.

In the previous example, the foo () function is in the global scope (here the window object), so the value of this is the current window object. In the form of new foo (), a copy of foo () is created and operated on the copy. Therefore, this is foo ().

This may be a bit abstract. Let's take a look at the actual example:

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.