博客
关于我
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/

    你可能感兴趣的文章
    POJ 2484 A Funny Game(神题!)
    查看>>
    POJ 2486 树形dp
    查看>>
    POJ 2488:A Knight's Journey
    查看>>
    SpringBoot为什么易学难精?
    查看>>
    poj 2545 Hamming Problem
    查看>>
    poj 2723
    查看>>
    poj 2763 Housewife Wind
    查看>>
    Qt笔记——模型/视图MVD 文件目录浏览器软件
    查看>>
    POJ 2892 Tunnel Warfare(树状数组+二分)
    查看>>
    poj 2965 The Pilots Brothers' refrigerator-1
    查看>>
    poj 3026( Borg Maze BFS + Prim)
    查看>>
    POJ 3041 - 最大二分匹配
    查看>>
    POJ 3041 Asteroids(二分匹配模板题)
    查看>>
    Qt笔记——标准文件对话框QFileDialog
    查看>>
    poj 3083 Children of the Candy Corn
    查看>>
    POJ 3083 Children of the Candy Corn 解题报告
    查看>>
    POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
    查看>>
    Qt笔记——控件总结
    查看>>
    poj 3262 Protecting the Flowers 贪心
    查看>>
    poj 3264(简单线段树)
    查看>>