這篇文章主要介紹js使用構造函數的缺點有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
1、不是原型鏈繼承,只是借用構造函數,所以不能繼承原型的屬性和方法。
2、雖然構造函數中定義的屬性和方法是可以訪問的,但是每個實例都被復制了。
如果例子太多,方法太多,占用內存很大,那么方法就在構造函數中定義,函數的復用就無從談起。
實例
// 父構造函數
function Father() {
this.name = 'father'
this.speakName1 = function () {
console.log('speakName1')
}
this.speakName2 = function () {
console.log('speakName2')
}
this.speakName3 = function () {
console.log('speakName3')
}
this.speakName4 = function () {
console.log('speakName4')
}
}
// 父原型上 方法
Father.prototype.alertName = function () {
console.log(this.name)
}
// 父原型上 屬性
Father.prototype.age = 21
// 子構造函數
function Children() {
Father.call(this)
}
// 創建子實例
let c1 = new Children()
// 調用原型方法,實例訪問不到
c1.alertName()
// TypeError: c1.alertName is not a function
// 訪問原型屬性,實例中未定義
console.log(c1.age)
// undefined
// 可以訪問實例屬性,但是每個實例都存有自己一份 name 值
console.log(c1.name)
// father
// 可以訪問實例方法,但是每個實例都存有自己一份 speakName1() 方法,
// 且方法過多,內存占用量大,這就不叫復用了
c1.speakName1()// speakName1
c1.speakName2()// speakName2
c1.speakName3()// speakName3
c1.speakName4()// speakName4
// instanceof isPrototypeOf 無法判斷實例和類型的關系
console.log(Father.prototype.isPrototypeOf(c1))// false
console.log(c1 instanceof Father)// false以上是“js使用構造函數的缺點有哪些”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。