js类class的继承和重写

2022-05-16  本文已影响0人  可乐不可乐_6e02

直接跑一下这段代码及注释,看下控制台的输出

  class Person {
    constructor(name, age) {
      this.name = name;
      this.age = age;
    }
    say() {
      return '我的名字是' + this.name;
    }

    set birth(value) {
      this._birth = `${value}-`;
    }
    get birth() {
      return this._birth;
    }
  }

  class Animal extends Person {
    // 继承拿到所有Person的属性
    constructor(name, age) {
      super(name, age) // 继承name
      this.age1 = age  // 通过继承的属性新建一个属性
    }
    say() {      // 重写say这个函数
      return 'My name is' + this.name;
    }
  }
  const animal = new Animal('嘻嘻', 5);   // 实例化对象并赋值
  const person = new Person('哈哈', 11);
  console.log('animal', animal);
  console.log('person', person);
  person.birth = 123;    // 相当于用set赋值
  console.log('birth', person.birth); // get拿到值
  console.log('birth', person.say);
  console.log('birth', animal.say);
上一篇 下一篇

猜你喜欢

热点阅读