這篇文章給大家分享的是有關js如何使用作用域安全的構造函數的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
作用域安全的構造函數
構造函數其實就是一個使用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); //undefinedconsole.log(window.name);//matchwindow的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 Polygo感謝各位的閱讀!關于“js如何使用作用域安全的構造函數”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。