es6学习整理(2)
class 语法糖
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(1,2))
js构造函数用法:
function MathHandle(x,y){
this.x = x;
this.y = y;
}
MathHandle.prototype.add = function(){
return this.x+this.y
}
const m = new MathHandle(1,2)
console.log(m.add(1,2))
构造函数 MathHandle
MathHandle.prototype.constructor === MathHandle
m.__proto__ === MathHandle.prototype
class 继承
class Animal{
constructor(name){
this.name = name
}
eat(){
console.log(`${this.name}eat`)
}
}
class Dog extends Animal{
constructor(name){
super(name)
this.name = name
}
say(){
console.log(`${this.name}say`)
}
}
const dog = new Dog('哈士奇')
dog.say()
dog.eat()
注意:class 后面跟extends 的写法一定要在constructor中吧super写上