Problem Introduction:
Before see "JS language Essence", introduce the dross of JS language, one of them is the global object . When you use a constructor, you may forget to write new, and the object is added to the Global object window, causing an unexpected increase in the Error object properties.
For example, a constructor:
function Person (gender,age) {
this.gender = gender;
This.age = age;
}
The correct way to open it should be var p = new Person (), which points to the newly created object. But when you forget to use new, such as var p1 = person (), the equivalent of calling the function directly, this points to the global object.
var p = new Person (' female ',);
Console.log (P.gender); Wei
console.log (window.gender);//undefined
var p1 = person (' male ', n);
Console.log (P1.gender); Error,p1 is undefined
console.log (window.gender);//xiao
scoped Security Constructor : Returns a new instance of person regardless of whether or not to use new.
function Polygon (sides) {if (this instanceof Polygon) {this.sides = sides;
This.getarea = function () {return 0;
} else {return new Polygon (name);
} function Rectangle (width, height) {Polygon.call (this, 2);//Borrow constructor this.width = width;
This.height = height;
This.getarea = function () {return this.width * this.height; } Rectangle.prototype = new Polygon ();
Prototype chain inheritance, which implements the rectangle instance is also a Polygon instance, thereby passing the checksum of ' if (this instanceof Polygon) ' in the Polygon constructor.
var rect = new Rectangle (5,10); alert (rect.sides);