初探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)行時的 this 指向,但是父類原型鏈上的屬性并沒有被繼承,是不完全的繼承
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)繼承
原理:原型鏈,但是在一個子類實(shí)例中改變了父類中的屬性,其他實(shí)例中的該屬性也會改變子,也是不完全的繼承
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'
}
// 避免父級的構(gòu)造函數(shù)執(zhí)行兩次,共用一個 constructor
// 但是無法區(qū)分實(shí)例屬于哪個構(gòu)造函數(shù)
// Child.prototype = Parent.prototype
// 改進(jìn):創(chuàng)建一個中間對象,再修改子類的 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)知識,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
JavaScript觸發(fā)onScroll事件的函數(shù)節(jié)流詳解
這篇文章的內(nèi)容是說說最近在工作中遇到過的常見的問題。主要是關(guān)于JavaScript觸發(fā)onScroll事件的函數(shù)節(jié)流,文中由一個常見的問題開始展開,一步步的介紹解決的方法,有需要的朋友們下面來跟著小編一起看看吧。2016-12-12
javascript判斷數(shù)組內(nèi)是否重復(fù)的方法
這篇文章主要介紹了javascript判斷數(shù)組內(nèi)是否重復(fù)的方法,涉及javascript針對數(shù)組的相關(guān)操作技巧,非常具有實(shí)用價值,需要的朋友可以參考下2015-04-04
JavaScript 關(guān)鍵字屏蔽實(shí)現(xiàn)函數(shù)
JavaScript屏蔽關(guān)鍵字,大概的思路就是去用javascript去替換已有的文本,達(dá)到替換的目的2009-08-08
fix-ie5.js擴(kuò)展在IE5下不能使用的幾個方法
fix-ie5.js擴(kuò)展在IE5下不能使用的幾個方法...2007-08-08
JavaScript數(shù)據(jù)類型及相互間的轉(zhuǎn)換規(guī)則
這篇文章主要介紹了JavaScript數(shù)據(jù)類型及相互間的轉(zhuǎn)換規(guī)則,文章通過圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09

