Class和普通構(gòu)造函數(shù)有何區(qū)別
前端會使用ES6中的Class來代替JS中的構(gòu)造函數(shù)
JS 構(gòu)造函數(shù)
function MathHandle(x,y){ //構(gòu)造函數(shù)
this.x = x;
this.y = y;
}
MathHandle.prototype.add = function(){ //原型的拓展
return this.x + this.y;
};
var m = new MathHandle(1,2); //實例化構(gòu)造函數(shù)
console.log(m.add)
Class 語法
class MathHandle {
constructor(x, y) { //構(gòu)造器
this.x = x
this.y = y
}
add() {
return this.x + this.y
}
}
const m = new MathHandle(1, 2)
console.log(m.add())
語法糖
兩種語法的本質(zhì)是一樣的,只是兩種格式不同。
class MathHandle{
//.......
}
typeof MathHandle //'function'
//class MathHandle的本質(zhì)是function
MathHandle === MathHandle.prototype.constructor //true
m.__proto__ === MathHandle.prototype //true 實例的隱式原型等于構(gòu)造函數(shù)的顯示原型
繼承 - JS
function Animal(){
this.name = name
this.eat = function(){
console.log('eat')
}
}
function Dog(){
this.bark = function(){
console.log('bark')
}
}
Dog.prototype = new Animal() //綁定原型 實現(xiàn)繼承
var hasiqi = new Dog()
hasiqi.bark()
hasiqi.eat()
繼承 - Class
class Animal{
constructor(name){
this.name = name
}
eat(){
console.log('eat')
}
}
class Dog extends Animal{
constructor(name){
super(name) //將name傳到Animal的constructor構(gòu)造器中去
this.name = name
}
say(){
console.log('say')
}
}
const dog= new Dog('哈士奇')
dog.say()
dog.eat()
總結(jié)
- Class在語法上更加貼近面向?qū)ο蟮膶懛?/li>
- Class在實現(xiàn)繼承更加易讀、易理解
- 更易于寫java等后端語言的使用
- Class本質(zhì)是語法糖,還是使用prototype的繼承方式