Scope problems of variables in JavaScript constructors

Source: Internet
Author: User

The constructor can be used with new, representing the creation of an object, or as a normal function call because it is also a function.

function person (name) {this.name=name;} Person (n); alert (window.name);//12

You can see that this represents a global window object when the constructor is called as a normal function. Obviously it is not a good practice to call a constructor function as a normal function, and there is no reason to do so. In practice, such strange usages should be eliminated in order not to produce strange problems.

function Person (name,sex) {    this.name=name;    var name1= "a";    Name2=sex;} var per = new Person ("Aty", "Boy"), alert (per.name),//Atyalert (PER.NAME1);//undefinedalert (per.name2);// Undefinedalert (window.name2);//boy

The constructor defines the variable using this is a member variable; var is a local variable, and no keyword is a global variable that is added to the Window object. This explains why the This keyword is used in constructors.

Scope problems of variables in JavaScript constructors

Related Article

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.