ES6 class and extends (类于类的继承)

单独的类可以用 class 来创建,然后再用 new 实例化,以下为 ES6 语法,代码如下:

  1. class Chef {
  2. constructor(food){
  3. this.food = food || "potato";
  4. }
  5. cook(){
  6. console.log(this.food); //. tomato
  7. }
  8. }
  9. let userOne = new Chef("tomato")

当我们需要继承一个类的时候,我们可以用 extends 进行类的继承,然后再用 new 实例化即可,代码如下:

  1. class P {
  2. constructor(name,birthday){
  3. this.name = name||"xiao";
  4. this.birthday = birthday||"1993-06-12";
  5. }
  6. intro(){
  7. return `${this.name},${this.birthday}`;
  8. }
  9. }
  10. class C extends P {
  11. constructor (name,birthday){
  12. super(name,birthday);
  13. }
  14. }
  15. let userTwo = new C();
  16. console.log(userTwo.intro()); //. xiao,1993-06-12
  17. let userT = new C("wang","1990-02-30");
  18. console.log(userT.intro()); //. wang,1990-02-30

评论: