相当于使用__proto__?

时间:2017-02-03 20:44:04

标签: javascript inheritance revealing-module-pattern

我试图使用带继承的揭示模块模式。我似乎工作正常,但它使用" __ proto __",我理解它被认为已被弃用。有没有更好的方法来创建继承而不使用" __ proto __"?

var Person = (function() {
    var _name;
    var api = {
        init: init,
        getName: getName
    }
    return api;

    function init(name) {
        _name = name;
    }

    function getName() {
        return _name;
    }
}())

var Teacher = (function() {
    var _subject = "Math";
    var api = {
        getSubject: getSubject,
        say: say
    }
    api.__proto__ = Person;
    return api;

    function getSubject() {
        return _subject;
    }

    function say() {
        console.log("I am " + this.getName() + " and I teach " + _subject)
    }
}());

Teacher.init("Bob");
Teacher.say() //  I am Bob and I teach math

https://plnkr.co/edit/XbGx38oCyvRn79xnn2FR?p=preview

1 个答案:

答案 0 :(得分:4)

直接等效 - 设置原型,仍然是个坏主意 - 是Object.setPrototypeOf

Object.setPrototypeOf(api, Person);

基于具有Object.create的原型创建对象然后向其添加属性的常规方法在这里工作正常,但是:

var api = Object.create(Person);
api.getSubject = getSubject;
api.say = say;

但理想情况下,您只需使用构造函数:

class Person {
    constructor(name) {
        this._name = name;
    }

    getName() {
        return this._name;
    }
}

class Teacher extends Person {
    constructor(name) {
        super(name);
        this._subject = 'Math';
    }

    getSubject() {
        return this._subject;
    }

    say() {
        console.log(`I am ${this.getName()} and I teach ${this.getSubject()}`);
    }
}

var teacher = new Teacher('Bob');
teacher.say() //  I am Bob and I teach math

没有ES6:

function Person(name) {
    this._name = name;
}

Person.prototype.getName = function () {
    return this._name;
};

function Teacher(name) {
    Person.call(this, name);
    this._subject = 'Math';
}

Teacher.prototype = Object.create(Person.prototype);

Teacher.prototype.getSubject = function () {
    return this._subject;
};

Teacher.prototype.say = function () {
    console.log('I am ' + this.getName() + ' and I teach ' + this.getSubject());
};

var teacher = new Teacher('Bob');
teacher.say();  // I am Bob and I teach math
相关问题