Scope-safe constructor
The constructor is actually a function called using the new operator
function Person(name,age,job){ this.name=name; this.age=age; this.job=job; } var person=new Person('match',28,'Software Engineer'); console.log(person.name);//match
If the new operator is not used, the three attributes originally targeted at the Person object are added to the window object
function Person(name,age,job){ this.name=name; this.age=age; this.job=job; } var person=Person('match',28,'Software Engineer'); console.log(person);//undefined console.log(window.name);//match
The name attribute of the window is used to identify the link target and frame Yes, accidental overwriting of this property here may cause other errors on the page. The solution to this problem is to create a scope-safe constructor
function Person(name,age,job){ if(this instanceof Person){ this.name=name; this.age=age; this.job=job; }else{ return new Person(name,age,job); } } var person=Person('match',28,'Software Engineer'); console.log(window.name); // "" console.log(person.name); //'match' var person= new Person('match',28,'Software Engineer'); console.log(window.name); // "" console.log(person.name); //'match'
However, Inheriting the constructor stealing pattern will have side effects. This is because, in the following code, this object is not a Polygon object instance, so the constructor Polygon() will create and return a new instance
function Polygon(sides){ if(this instanceof Polygon){ this.sides=sides; this.getArea=function(){ return 0; } }else{ return new Polygon(sides); } } function Rectangle(wifth,height){ Polygon.call(this,2); this.width=this.width; this.height=height; this.getArea=function(){ return this.width * this.height; }; } var rect= new Rectangle(5,10); console.log(rect.sides); //undefined
If you want If you use the scope-safe constructor to steal the pattern, you need to combine prototype chain inheritance and rewrite the prototype attribute of Rectangle so that its instance also becomes an instance of Polygon
##
function Polygon(sides){ if(this instanceof Polygon){ this.sides=sides; this.getArea=function(){ return 0; } }else{ return new Polygon(sides); } } function Rectangle(wifth,height){ Polygon.call(this,2); this.width=this.width; this.height=height; this.getArea=function(){ return this.width * this.height; }; } Rectangle.prototype= new Polygon(); var rect= new Rectangle(5,10); console.log(rect.sides); //2
The above is the detailed content of Detailed explanation of scope safe constructor example code in JavaScript. For more information, please follow other related articles on the PHP Chinese website!