es6 Class基本语法和继承

es6 Class基本语法

class的基本语法:
ES6 的class只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已

传统用构造函数生成实例

function Point(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
}

var p = new Point(1, 2);

es6 class写法
constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

Class的继承

通过extends关键字实现继承,ES6 规定,子类必须在constructor()方法中调用super(),否则就会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,添加子类自己的实例属性和方法。如果不调用super()方法,子类就得不到自己的this对象
为什么子类的构造函数,一定要调用super()?原因就在于 ES6 的继承机制,与 ES5 完全不同。ES5 的继承机制,是先创造一个独立的子类的实例对象,然后再将父类的方法添加到这个对象上面,即“实例在前,继承在后”。ES6 的继承机制,则是先将父类的属性和方法,加到一个空的对象上面,然后再将该对象作为子类的实例,即“继承在前,实例在后”。这就是为什么 ES6 的继承必须先调用super()方法,因为这一步会生成一个继承父类的this对象,没有这一步就无法继承父类。

class Point { 
	constructor(x, y) {
	    this.x = x;
	    this.y = y;
	}
	toString() {
	    return '(' + this.x + ', ' + this.y + ')';
	}
 }

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // 调用父类的toString()
  }
}

es5原型链实现继承

function SuperType() {
  this.property = true
}
SuperType.prototype.getSuperValue = function() {
  return this.property
}
function SubType() {
  this.subproperty = false
}
// 继承了SuperType
SubType.prototype = new SuperType()
SubType.prototype.getSubValue = function() {
  return this.subproperty
}

const instance = new SubType()
alert(instance.getSuperValue()) // true

在这里插入图片描述

构造函数、原型和实例的关系
在这里插入图片描述

相关推荐

  1. ES6中如何使用classextends关键字实现继承

    2024-03-30 10:12:02       8 阅读
  2. ES6基础语法

    2024-03-30 10:12:02       40 阅读
  3. es6基础语法

    2024-03-30 10:12:02       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-30 10:12:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-30 10:12:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-30 10:12:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-30 10:12:02       18 阅读

热门阅读

  1. CentOS 7.9上安装Redis

    2024-03-30 10:12:02       19 阅读
  2. 贪心,LeetCode 2952. 需要添加的硬币的最小数量

    2024-03-30 10:12:02       21 阅读
  3. 大型网站的容灾备份和高可用的详细技术和示例

    2024-03-30 10:12:02       19 阅读
  4. TCP的keepalive与HTTP的keep-alive的区别

    2024-03-30 10:12:02       19 阅读
  5. 实验十 枚举问题(过程模拟)

    2024-03-30 10:12:02       17 阅读
  6. YOLOv8参数详解

    2024-03-30 10:12:02       30 阅读
  7. sql中如何添加数据

    2024-03-30 10:12:02       19 阅读
  8. go中匿名函数的使用

    2024-03-30 10:12:02       21 阅读
  9. 如何解决EventSource 删除单词的前置空格问题

    2024-03-30 10:12:02       16 阅读