ES6 class实现继承
一、声明父类
class Phone{
constructor(name,price){
this.name = name;
this.price = price;
}
// 父类的方法
play(){
console.log("我可以玩游戏");
}
}
二、声明子类
- 使用extends关键字继承父类
- 通过super调用父类的构造方法
class SmartPhone extends Phone{
constructor(name,price,color){
// super就是父类的constructor方法
//与ES5的 Phone.call(this,name,price)效果一样
super(name,price);
this.color = color;
}
//子类的方法
photo(){
console.log("拍照");
}
}
四、实例化一个子类
const oppo = new SmartPhone('Find x5','¥4799','紫色');
console.log(oppo);//Object { name: "Find x5", price: "¥4799", color: "紫色" }
- 查看属性
-
子类自身的方法
-
从父类继承的方法
总结
写法比ES5更简洁,贴合传统语言的继承写法