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.