The This mechanism in JavaScript-basic knowledge

Source: Internet
Author: User

JavaScript has its own set of this mechanism, in different cases, this point is not the same.

Global scope

Console.log (this); Global variables

The global scope uses this to point to the global variable, which is window in the browser environment.

Note: The ECMAScript5 strict mode does not have global variables, here is undefined.

In a function call

function foo () {
  console.log (this);
}

Foo (); Global variables

This in the function call also points to the global variable.

Note: The ECMAScript5 strict mode does not have global variables, here is undefined.

Object method call

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

Test.foo (); Test object

Object method call, this points to the caller.

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

var test2 = Test.foo;
Test2 (); Global variables

However, because of this late binding attribute, in the case of the example, this will point to the global variable, which is equivalent to calling the function directly.

This is very important, the same code snippet, only at run time can you determine this point

Constructors

function Foo () {
  console.log (this);
}

New Foo (); The newly created object
console.log (foo); 

Inside the constructor, this points to the newly created object.

Explicitly set this

function foo (A, b) {
  console.log (this);
}

var bar = {};

Foo.apply (Bar, [1, 2]); Bar
Foo.call (1, 2);//number Object

The call or Apply method using Function.prototype is that the inside of the function is set to the first argument passed in.

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.