Usage of this in JavaScript

Source: Internet
Author: User

This is a keyword in the JavaScript language.

It represents an internal object that is automatically generated when the function is run, and can only be used inside a function. Like what

function test () {
    
this.x = 1;
    
}

The value of this will change as the function is used differently. But there is a general principle, and that is this refers to the object that invokes the function.

Here are four different scenarios for a detailed discussion of this usage.

Case one: pure function call

This is the most common use of a function, which is a global call, so this represents the globally object.

Take a look at the code below and it runs 1.

function test () {
    
this.x = 1;
    
alert (this.x);
    
}
    
Test (); 1

To prove that this is the global object, I make some changes to the code:

var x = 1;
    
function test () {
    
alert (this.x);
    
}
    
Test (); 1

The results of the operation are still 1. Change again:

var x = 1;
    
function test () {
    
this.x = 0;
    
}
    
Test ();
    
alert (x); 0

Case two: Call as an object method

A function can also be invoked as a method of an object, at which point this is the ancestor object.

function test () {
    
alert (this.x);
    
}
    
var o = {};
    
o.x = 1;
    
O.M = test;
    
O.M (); 1

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

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.