javascript使用的是原型式继承,我们可以通过原型的特性实现类的继承,
es6为我们提供了像面向对象继承一样的语法糖。
1.类的实现
class底层仍然是构造函数
- 调用_classCallCheck方法判断当前函数调用前是否有new关键字
- 将class内部的变量和函数赋给this
- 执行构造器内部逻辑
- return this
2.继承实现
var Child = function (_Parent) { _inherits(Child, _Parent); function Child(a, b) { _classCallCheck(this, Child); var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this, a)); _this.filed4 = 1; _this.func2 = function () {}; _this.filed3 = b; return _this; } return Child; }(Parent);
- 调用_inherits函数继承父类的proptype
- 用一个闭包保存父类引用,在闭包内部做子类构造逻辑
- new检查
- 用当前this调用父类构造函数
- 将行子类class内部的变量和函数赋给this。
- 执行子类constuctor内部的逻辑
- es6实际上是为我们提供了一个“组合寄生继承”的简单写法。