The This in JS

Source: Internet
Author: User

Writing this blog is because of the previous time encountered some of the problem to get yourself foggy.

This is a keyword in the JS computer language. It represents an internal object that is automatically generated when the function is run, and can only be used inside the function (it has different meanings in different places).

Below are three kinds of situations, discussed in detail (personal to) this use of some understanding, interested friends can understand the next

This is a key word for the JS computer language.
It represents an internal object that is automatically generated when the function is run, and can only be used inside the function.

function A () {

this.x = 1;

}

The value of this will change when the function is used in different situations. But there is a general rule, that is, this is the object that invokes the function (this is the meaning of ' this ').

The most common use of a function, which is a global call, so this represents a Globals object

Window.onload=function () {

Test ();

}

function A () {

this.x = 1;

Console.log (this.x);

}

function can also act as a method call to an object, this is the parent object

function A () {

Console.log (this.x);

}

var tmp = {};

tmp. x = 1;

tmp. y = test;

tmp. Y ();

The call to the constructor, the constructor, is to generate a new object by this function (object). At this point, this is the new object).

function A () {

this.x = 1;

}

var temp = new Test ();

Console.log (temp.x);


The This in JS

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.