Do you understand the object in Javascript that this is pointing to?

Source: Internet
Author: User

This is always confusing in Javascript, can you tell the output of the following three kinds of test1 (), Test2 (), Test3 ()?

Note: The following JavaScript is in the running environment for the browser

1 This is used in global functions

var x = 1;

function Test1 () {

var x = 5;

alert (this.x);

}

function _test2 () {

This.x = 5;

alert (this.x);

}

2 This is used in the constructor in new

function Test2 () {

var f = new _test2 ();

}

3 This is used in methods of the object

function _test3 () {

Alert (this.x)

}

function Test3 () {

var a = {};

a.x = 100;

A.show = _test3;

A.show ();

}

Figuring out the key to this point is:

function is used in different situations, this the value will change. But there is a general principle, that is , this refers to the object that called the function.

    1. Test1 Call Scenario: equivalent to Window.test1 (), alert shows the value of the calling function X, which is window.x
    2. Test2 the called scene: when the new keyword is generated, the object that this point refers to is the newly generated object _test2 ().
    3. TEST3 Invocation Scenario: The function acts as a method call to an object, and this refers to the ancestor object, which is a

Do you understand the object in Javascript that this is pointing to?

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.