問題引入:
之前看到《js語言精粹》上,介紹js語言的糟粕,其中之一就是全局對象。當在使用構造函數時,可能忘記寫new,那對象就添加到了全局對象window上,導致了錯誤對象屬性的意外增加。
比如,一個構造函數:
function Person(gender,age){
this.gender = gender;
this.age = age;
}
正確的打開方式應該是var p = new Person()
,this指向新創建的對象。但是當忘記使用new時,如var p1 = Person()
, 相當於直接調用函數,this指向全局對象。
var p = new Person('女',18);
console.log(p.gender); //wei
console.log(window.gender); //undefined
var p1 = Person('男',23);
console.log(p1.gender); //Error,p1爲undefined
console.log(window.gender); //xiao
作用域安全的構造函數:不論是否使用new,都返回一個Person的新實例。
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); //借用構造函數
this.width = width;
this.height = height;
this.getArea = function() {
return this.width * this.height;
}
}
Rectangle.prototype = new Polygon(); //原型鏈繼承,實現Rectangle實例也是一個Polygon實例,從而通過Polygon構造函數中`if (this instanceof Polygon)`的校驗。
var rect = new Rectangle(5,10);
alert(rect.sides);