ES5 prototype
function Dog(name){
this.name = name
this.legs = 4
}
Dog.prototype.say = function(){
console.log(`${this.name} - ${this.legs}`)
}
Dog.prototype.kind = '狗'
const d1 = new Dog('tom')
const d2 = new Dog('jimmy')
d1.say()
d2.say()
在prototype中放置可共享的屬性(避免內(nèi)存浪費),在函數(shù)中放置各自的私有屬性
ES6 class
class Dog {
kind = '狗'
constructor(name){
this.name = name
this.legs = 4
}
say(){
}
run(){
}
}
const d1 = new Dog('jimmy')
d1.say()
js原型鏈繼承的實現(xiàn)
function Animal(legsNumber){
this.legsNumber = legsNumber
}
Animal.prototype.kind = '動物'
function Dog(name){
Animal.call(this,4) // this.legsNumber = 4
this.name = name
}
// Dog.prototype.__proto__ = Animal.prototype 不是所有瀏覽器都存在__proto__屬性
var emptyAnimal = function(){}
emptyAnimal.prototype = Animal.prototype
Dog.prototype = new emptyAnimal()
Dog.prototype.say = function(){
console.log(`${this.name} - ${this.legs}`)
}
Dog.prototype.kind = '狗'
new的作用:
- 創(chuàng)建臨時對象
- this = 臨時對象
- 'this.proto' = 構(gòu)造函數(shù)的prototype
- 執(zhí)行構(gòu)造函數(shù)
- return this
我們希望執(zhí)行上面的1,2箕速,3锅风,5殖蚕,因為4在我們聲明Dog時已經(jīng)使用,所以我們需要構(gòu)建一個空的函數(shù)體的emptyAnimal节吮,然后我們執(zhí)行Dog.prototype = new emptyAnimal()就能完成繼承
es6 class 繼承
class Animal {
constructor(legsNumber){
this.legsNumber = legsNumber
}
run(){}
}
class Dog extends Animal{
constructor(name){
super(4)
this.name = name
}
say(){
console.log(`${this.name} ${this.legsNumber}`)
}
}