掩耳倾听

文章 评论 浏览 27

掩耳倾听 2022-05-04 13:57:31

我觉得忽略了一点,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)

测试了两种继承 子类实例的行为是一致的。

第 7 题:ES5/ES6 的继承除了写法以外还有什么区别?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文