初探JavaScript 面向?qū)ο?推薦)
類的聲明
1. 構(gòu)造函數(shù)
function Animal() { this.name = 'name' } // 實(shí)例化 new Animal()
2. ES6 class
class Animal { constructor() { this.name = 'name' } } // 實(shí)例化 new Animal()
類的繼承
1. 借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承
原理:改變子類運(yùn)行時(shí)的 this 指向,但是父類原型鏈上的屬性并沒(méi)有被繼承,是不完全的繼承
function Parent() { this.name = 'Parent' } Parent.prototype.say = function(){ console.log('hello') } function Child() { Parent.call(this) this.type = 'Child' } console.log(new Parent()) console.log(new Child())
2. 借助原型鏈實(shí)現(xiàn)繼承
原理:原型鏈,但是在一個(gè)子類實(shí)例中改變了父類中的屬性,其他實(shí)例中的該屬性也會(huì)改變子,也是不完全的繼承
function Parent() { this.name = 'Parent' this.arr = [1, 2, 3] } Parent.prototype.say = function(){ console.log('hello') } function Child() { this.type = 'Child' } Child.prototype = new Parent() let s1 = new Child() let s2 = new Child() s1.arr.push(4) console.log(s1.arr, s2.arr) console.log(new Parent()) console.log(new Child()) console.log(new Child().say())
3. 構(gòu)造函數(shù) + 原型鏈
最佳實(shí)踐
// 父類 function Parent() { this.name = 'Parent' this.arr = [1, 2, 3] } Parent.prototype.say = function(){ console.log('hello') } // 子類 function Child() { Parent.call(this) this.type = 'Child' } // 避免父級(jí)的構(gòu)造函數(shù)執(zhí)行兩次,共用一個(gè) constructor // 但是無(wú)法區(qū)分實(shí)例屬于哪個(gè)構(gòu)造函數(shù) // Child.prototype = Parent.prototype // 改進(jìn):創(chuàng)建一個(gè)中間對(duì)象,再修改子類的 constructor Child.prototype = Object.create(Parent.prototype) Child.prototype.constructor = Child // 實(shí)例化 let s1 = new Child() let s2 = new Child() let s3 = new Parent() s1.arr.push(4) console.log(s1.arr, s2.arr) // [1, 2, 3, 4] [1, 2, 3] console.log(s2.constructor) // Child console.log(s3.constructor) // Parent console.log(new Parent()) console.log(new Child()) console.log(new Child().say())
總結(jié)
以上所述是小編給大家介紹的JavaScript 面向?qū)ο?推薦)的相關(guān)知識(shí),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
相關(guān)文章
JavaScript canvas實(shí)現(xiàn)帶有陰影的圖形和文字
這篇文章主要為大家詳細(xì)介紹了JavaScript canvas實(shí)現(xiàn)帶有陰影的圖形和文字,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-03-03scroll事件實(shí)現(xiàn)監(jiān)控滾動(dòng)條并分頁(yè)顯示(zepto.js)
這篇文章主要為大家詳細(xì)介紹了scroll事件實(shí)現(xiàn)監(jiān)控滾動(dòng)條并分頁(yè)顯示示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12微信小程序配置視圖層數(shù)據(jù)綁定相關(guān)示例
這篇文章主要為大家介紹了微信小程序配置視圖層數(shù)據(jù)綁定相關(guān)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪<BR>2022-04-04js實(shí)現(xiàn)簡(jiǎn)單隨機(jī)抽獎(jiǎng)的方法
這篇文章主要介紹了js實(shí)現(xiàn)簡(jiǎn)單隨機(jī)抽獎(jiǎng)的方法,涉及字符串的操作、setInterval定時(shí)調(diào)用等技巧,需要的朋友可以參考下2015-01-01javascript 中的 delete及delete運(yùn)算符
這篇文章主要介紹了javascript 中的 delete及delete運(yùn)算符的相關(guān)資料,需要的朋友可以參考下2015-11-11