Class和普通构造函数有何区别
前端会使用ES6中的Class来代替JS中的构造函数
JS 构造函数
function MathHandle(x,y){ //构造函数
this.x = x;
this.y = y;
}
MathHandle.prototype.add = function(){ //原型的拓展
return this.x + this.y;
};
var m = new MathHandle(1,2); //实例化构造函数
console.log(m.add)
Class 语法
class MathHandle {
constructor(x, y) { //构造器
this.x = x
this.y = y
}
add() {
return this.x + this.y
}
}
const m = new MathHandle(1, 2)
console.log(m.add())
语法糖
两种语法的本质是一样的,只是两种格式不同。
class MathHandle{
//.......
}
typeof MathHandle //'function'
//class MathHandle的本质是function
MathHandle === MathHandle.prototype.constructor //true
m.__proto__ === MathHandle.prototype //true 实例的隐式原型等于构造函数的显示原型
继承 - JS
function Animal(){
this.name = name
this.eat = function(){
console.log('eat')
}
}
function Dog(){
this.bark = function(){
console.log('bark')
}
}
Dog.prototype = new Animal() //绑定原型 实现继承
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构造器中去
this.name = name
}
say(){
console.log('say')
}
}
const dog= new Dog('哈士奇')
dog.say()
dog.eat()
总结
- Class在语法上更加贴近面向对象的写法
- Class在实现继承更加易读、易理解
- 更易于写java等后端语言的使用
- Class本质是语法糖,还是使用prototype的继承方式