美文网首页
js类class的继承和重写

js类class的继承和重写

作者: 可乐不可乐_6e02 | 来源:发表于2022-05-16 13:46 被阅读0次

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

  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);

相关文章

  • js类class的继承和重写

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

  • 继承和接口

    继承(class 子类 extends 父类)Override:方法重写只改动方法体。 继承不能继承父类私有属性及...

  • 多线程实现方式

    1、继承Thread类,重写run方法。 public class MyThread extends Thread...

  • TypeScript - 04 类

    类 上面等同于原生js 继承 class A extends B,A类继承B类所有的属性和方法 子类通过 supe...

  • swift中的继承

    只有类支持继承 重写实例方法、下标 重写类型方法、下标 用class修饰的可以被重写 重写属性 1.重写实例属性 ...

  • Swift - 类、初始化器

    class和struct的区别 1.结构体是值类型,不能继承 2.类是引用类型,可以继承 3.类可以重写方法以及属...

  • 4、Typescript类的继承和修饰符

    1、ts中类的定义使用关键字class、继承使用 extends 和 super 2、子类方法名和父类相同表示重写...

  • java多线程的4种实现方式

    1,继承Thread类,重写run方法; public class Thread01 extends Thread...

  • 多线程编程

    一、创建线程 1.继承 Thread 类,重写 run() 方法栗子:public class TestThrea...

  • 线程的创建方式及使用

    1、继承thread类,重写run方法,直接调用.start()方法启动 public class Mythrea...

网友评论

      本文标题:js类class的继承和重写

      本文链接:https://www.haomeiwen.com/subject/vhfwurtx.html