前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >再理解es6 中的 class super extends

再理解es6 中的 class super extends

作者头像
西南_张家辉
发布2021-02-02 10:00:27
4530
发布2021-02-02 10:00:27
举报
文章被收录于专栏:张家辉的树屋

说明

  • 适用于 es6 初学者
  • 理解 class 的使用

extends 继承

  • class 可以通过 extends 关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。
代码语言:javascript
复制
class Point{
    
}

class ColorPoint extends Point{
    
}
复制代码

上面代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和方法。但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个Point类。下面,我们在ColorPoint内部加上代码。

super 调用父类 constructor

代码语言:javascript
复制
class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // 调用父类的toString()
  }
}
复制代码
  • super 来调用父类的 constructor

子类没有定义 constructor,会默认添加

代码语言:javascript
复制
class ColorPoint extends Point {
}

// 等同于
class ColorPoint extends Point {
  constructor(...args) {
    super(...args);
  }
}
复制代码

合理的使用 super

super 当做函数调用
  • 第一种情况,super 关键字作为函数调用。es6 中,子类的构造函数必须执行一次 super(记住我们可以不写 constructor 和 super ,函数会自动添加上,看
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • extends 继承
    • super 调用父类 constructor
      • 子类没有定义 constructor,会默认添加
        • 合理的使用 super
          • super 当做函数调用
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档