問題引入:
之前看到《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); //weiconsole.log(window.gender); //undefinedvar p1 = Person('男',23);console.log(p1.gender); //Error,p1為undefinedconsole.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);