Scope of variables in Javascript Constructor

Source: Internet
Author: User

Scope of variables in Javascript Constructor

Constructor can be used with new to create objects. It can also be called as a common function because it is also a function.

Function Person (name) {this. name = name;} Person (12); alert (window. name); // 12

This indicates the global window object when the constructor is called as a common function. It is obvious that the constructor is treated as a common function call. It is not a good practice and there is no reason to do so. In practice, we should avoid such strange usage to avoid strange problems.

Function Person (name, sex) {this. name = name; var name1 = "22"; name2 = sex;} var per = new Person ("aty", "boy"); alert (per. name); // atyalert (per. name1); // undefinedalert (per. name2); // undefinedalert (window. name2); // boy

The constructors define variables using this as member variables; var as local variables; without a keyword, this variable is added to the window object. This explains why the this keyword is used in constructors.

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.