This in JavaScript points to the problem

Source: Internet
Author: User

This keyword:

1, this points to the object that called the function

Typically, a variable, a function, is defined as the property of the window , the method's

Var info= ' Hello ';

Function Sayhi () {

This.style.color= ' Red ';

}

global variable info is actually window.info=' Hello ';

Calling Sayhi () is actually a window object in the call, that is, window.sayhi () usually omits the window , called directly. So this in this.style.color is pointing to window.

2. when instantiated with the new keyword, change this point and not point to window. Instead, it points to the instantiated object.

Example:

Function Student(){

This.name= "Lydia";

}

Var stu=new Student ();

This point points to Stu

3. Anonymous functions are global, so in anonymous functions this points to the window Object

Var name= ' outer ';

Var obj={

Name: ' Inner ',

Say:function () {

Alert (this.name); Inner This points to the object that is calling its function, obj

(Function () {

Console.log (this.name); Outer this point to window

}());

}

}

Obj.say ();

This in JavaScript points to the 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.