The pointer to this in JavaScript

Source: Internet
Author: User
Tags variable scope

This is the keyword of JS, and the This value will change as the function is used in different situations. But the general principle is that this always points to the object that is calling this function .

1. Pure function call

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

This is the global variable. The following example is a good way to understand that this is a global object.

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

In JavaScript's variable scope, "Global variables are all properties of a Window object." "So executing test () is equivalent to Window.test (), at which point the This keyword in the test function body becomes the window object. The X of the Window object will be changed to 0.

var x=1; var b={   x:2,   GetX:function() {      return  this. x;   }}; Alert (this. x);     // 1 // 2

In the above code, alert (this.x) in the this point to the window, so in the global search for the value of x, is 1;

Alert (B.getx ()) is called with the function of X as Object B, this points to B, so the value of x is searched for in B, which is 2.

2, as a method invocation, then this refers to the object that invokes the method.

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

3. Called as a constructor function. This point points to the newly generated object.

function Test () {   this. x=1;}  var New Test (); alert (o.x);   // 1

4, apply call. This points to the first parameter in apply.

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

When apply has no parameters, it is represented as a global object. So the value is 0.

The pointer to this in JavaScript

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.