The This keyword in JavaScript points to a problem

Source: Internet
Author: User

1. Purely function calls, this represents global objects

var x = 1; function Test () {    var x = ' er ha ';    Console.log (this. x);    // 1 }test ();

2, as a member method of an object, this represents the object

x = ' er ha ' ;
function Test () { console.log (this. x); //1} var obj = { 1, Fn:test}obj.fn ();

3, as a constructor call, this represents the new object that is generated by the ' new ' keyword

x = ' er ha ' ;
function Test () {
this. x = 1;} var New test (); Console.log (obj.x) // 1

4. When using the call () method or Apply (), the first parameter of this method is the object that called the function after the change, this refers to the first parameter, when the argument is empty, the global object is called by default

var x = 1; function Test () {Console.log (this. x);} var obj = {    ' er ha ',    fn:test};obj.fn.apply ();     // 1       

The This keyword in JavaScript points to a problem

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.