解析ES2015中的对象继承

从ES2015开始,我们可以使用extends关键字实现对象继承,使用super关键字指向父对象。比如下面的ES2015代码:

class Foo {
    constructor(id) {
        this.id = id;
    }

    show() {
        console.log('父类');
        console.log('id --- ' + this.id);
    }
}

class Bar extends Foo {
    constructor(id, name) {
        super(id);
        // 必须在使用`this`之前调用`super()`,否则会导致引用错误
        this.name = name;
    }

    show() {
        console.log('子类');
        super.show();
        console.log('name --- ' + this.name);
    }
}

var bar = new Bar(1, 'Jason');
bar.show();

上面代码的输出结果为:

子类
父类
id --- 1
name --- Jason

与我们之前文章谈到的一样,ES2015对textendssuper的实现,归根结底还是一种语法糖。那么在ES的环境下,我们应该如何实现对象继承呢?

ES5中的对象继承(方法一)

var Foo = function (id) {

    this.id = id;

    this.show = function () {
        console.log('父类');
        console.log('id --- ' + this.id);
    }
};

var Bar = function (id, name) {

    Foo.call(this, id);
    this.name = name;

    this.super = new Foo();

    this.show = function () {
        console.log('子类');
        this.super.show.call(this);
        console.log('name --- ' + this.name);
    };
};

var bar = new Bar(1, 'Jason');
bar.show();

ES5中的对象继承(方法二)

var Foo = function (id) {

    this.id = id;

    this.show = function () {
        console.log('父类');
        console.log('id --- ' + this.id);
    }
};

var Bar = function (id, name) {

    this.super.id = id;
    this.name = name;

    this.show = function () {
        console.log('子类');
        this.super.show();
        console.log('name --- ' + this.name);
    };
};

Function.prototype.extends = function (base) {
    base.call(this.prototype);
    this.prototype.super = new base();
};

Bar.extends(Foo);

var bar = new Bar(1, 'Jason');
bar.show();

你可能感兴趣的:(JavaScript)