用es5實現一個繼承
類式繼承
function Person () {
this.name = 'Person'
this.sex = 'male'
this.say = function () {
console.log('Person say')
}
}
function Student () {
Person.call(this) // 問題關鍵,改變執行上下文
this.name = 'Student'
this.privateAttr = '學生類的私有屬性'
this.say = function () {
console.log('Student say')
}
}
var stu = new Student()
var person = new Person()
原型繼承
function Animal () {
this.name = 'Animal'
this.sex = 'male'
}
Animal.prototype.say = function () {
console.log('Animal Say')
}
function Pig () {
this.name = 'Pig'
this.privateAttr = '豬的私有屬性'
}
Pig.prototype = new Animal()
Pig.prototype.constructor = Pig
Pig.prototype.eat = function () {
console.log(`${this.name} eat`)
}
var pig = new Pig()
var animal = new Animal()
組合繼承
function Fe () {
this.name = 'Fe'
this.zhName = '鐵'
}
Fe.prototype.say = function () {
console.log(this.name)
}
function Fe3O4 () {
Fe.call(this)
this.name = 'Fe3O4'
this.privateAttr = '四氧化三鐵 的私有屬性'
}
Fe3O4.prototype = new Fe()
Fe3O4.prototype.constructor = Fe3O4
var fe3o4 = new Fe3O4()
var fe = new Fe()
剛纔蹲在坑上聽網易音樂,發現bug還有一大堆沒寫,我啪啪啪打了自己幾巴掌,“聽歌呢,亂想啥” 一一網易某歌熱評