文章 评论 浏览 27
我觉得忽略了一点,es6的class继承不仅是对原型实例进行了继承,还对构造方法进行了继承,class本质还是一个构造函数,转码后的实现逻辑还是组合寄生继承。
没错,敲代码验证了一下:
ES5的寄生组合式继承:
function Foo(age){ this.age = age this.balls = [1,2,3] } Foo.prototype.getAge = function(){ return this.age } function Bar(name, age){ Foo.call(this, age) this.name = name } Bar.prototype = Object.create(Foo.prototype) Bar.prototype.constructor = Bar Bar.prototype.getName = function(){ return this.name } const b1 = new Bar('b1', 18) const b2 = new Bar('b2', 20)
对应的ES6 class的继承:
class Foo { constructor(age){ this.age = age this.balls = [1,2,3] } getAge(){ return this.age } } class Bar extends Foo { constructor(name, age){ super(age) this.name = name } getName(){ return this.name } } const b1 = new Bar('b1', 18) const b2 = new Bar('b2', 20)
测试了两种继承 子类实例的行为是一致的。
文章 0 评论 0
接受
没错,敲代码验证了一下:
ES5的寄生组合式继承:
对应的ES6 class的继承:
测试了两种继承 子类实例的行为是一致的。
第 7 题:ES5/ES6 的继承除了写法以外还有什么区别?