作用域安全的建構子
建構子其實就是一個用new運算子呼叫的函式
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
如果沒有使用new運算符,原本針對Person物件的三個屬性被加入到window物件
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
window的name屬性是用來識別連結目標和框架的,這裡對該屬性的偶然覆蓋可能會導致頁面上的其它錯誤,這個問題的解決方法就是創建一個作用域安全的構造函數
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'
但是,建構函數竊取模式的繼承,會帶來副作用。這是因為,在下列程式碼中,this物件並非Polygon物件實例,所以建構子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; }; } var rect= new Rectangle(5,10); console.log(rect.sides); //undefined
如果要使用作用域安全的建構子竊取模式的話,需要結合原型鏈繼承,重寫Rectangle的prototype屬性,使它的實例也變成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
以上是javascript中的作用域安全建構函式實例程式碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!