博客
关于我
ES6之class的继承
阅读量:194 次
发布时间:2019-02-28

本文共 882 字,大约阅读时间需要 2 分钟。

ES6类继承理解与实践——Man类详解

在前端开发中,理解类继承的机制是至关重要的。ES6引入了extends关键字,使类继承变得更加清晰和方便,这与传统的通过修改原型链实现继承相比,具有显著优势。

以下是一个典型的例子,展示了如何使用extends实现类继承:

class Human {  constructor(name) {    this.name = name;  }  run(mile) {    console.log(`我每小时能跑${mile}`);  }  static hello() {    console.log('hello world');  }}class Man extends Human {  constructor(name, age) {    super(name); // 必须先调用父类构造函数    this.age = age;  }}const man = new Man('小王', 22);console.log(man.name); // 小王console.log(man.age); // 22man.run(111); // 我每小时能跑111man.hello(); // hello world

注意以下关键点:

  • 子类构造函数的处理:在子类的构造函数中,必须先调用super(),否则会抛出ReferenceError。这是因为子类实例的构建依赖于父类实例的构建,super()方法才能调用父类构造函数。

  • 静态方法的继承:子类可以继承父类的静态方法。例如,Man.hello()可以直接调用Human.hello()的功能。

  • 属性的访问顺序:在子类实例中,this对象的属性和方法的初始化顺序是:先父类的属性被初始化,再执行子类的逻辑。

  • 这种实现方式相比传统的原型链继承,代码更加清晰,逻辑更加明确。通过合理使用extends,我们可以更方便地扩展和维护类的代码结构。

    如果你对前端开发感兴趣,欢迎加入我们的技术交流QQ群:327814892,和志同道合的朋友一起探讨更多有趣的技术内容!

    转载地址:http://utri.baihongyu.com/

    你可能感兴趣的文章
    pilicat-dfs 霹雳猫-分布式文件系统
    查看>>
    Pillow lacks the JPEG 2000 plugin
    查看>>
    SpringBoot之ElasticsearchRestTemplate常用示例
    查看>>
    ping 全网段CMD命令
    查看>>
    ping 命令的七种用法,看完瞬间成大神
    查看>>
    Pinia入门(快速上手)
    查看>>
    Pinia:$patch的使用场景
    查看>>
    Pinia:$subscribe()的使用场景
    查看>>
    Pinpoint对Kubernetes关键业务模块进行全链路监控
    查看>>
    Pinterest 大规模缓存集群的架构剖析
    查看>>
    pintos project (2) Project 1 Thread -Mission 1 Code
    查看>>
    PinYin4j库的使用
    查看>>
    PIP
    查看>>
    pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
    查看>>
    pip install mysqlclient报错
    查看>>
    pip install 出现报asciii码错误的解决
    查看>>
    pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
    查看>>
    pip 下载慢
    查看>>
    pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
    查看>>
    pip 安装opencv-python卡死
    查看>>