javascript面向物件程式設計--安全構造物件
建構函式 其實就是一種 使用new運算子的函式
function Person(name,age,job){
this.name=name;
this.age=age;
this.job=job;
}
var person=new Person("Owen",34,"codeworker");
如果沒有new,由於該this物件是在執行時繫結,直接使用Person會將該物件繫結到window上,即this解析成window
解決方案--安全構造物件
function Person(name,age,job){
if(this instanceof Person){ //檢測物件是否為Person的例項
this.name=name;
this.age=age;
this.job=job;
} else{
return new Person(name,age,job)
}
}
2.繼承時導致的不安全問題,如果使用的建構函式獲取繼承且不使用原型鏈,這個繼承會被破壞
function Polygon(sides){
if(this instanceof Polygon){
this.sides=sides;
this.getArea=function(){ return 0;}
}else{ return new Polygon(sides);}
}
function Rectangle(width,height){//此建構函式的作用域是不安全的
Polygon.call(this,2);//注意,由於Polygond的作用域是安全的,this並非是Polygon的例項,而是返回建立一個新的Polygon物件
this.width=width;
this.height=height;
this.getArea=function(){ return this.width*this.height;}
}
Rectangle.prototype=new Polygon();//增長react的this,
var rect=new Rectangle(5,10);
alert(rect.sides);//2,若沒有使用原型鏈則是undefined