javascript - 相当于使用 __proto__?

标签 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

最佳答案

直接的等价物——设置原型(prototype),仍然是一个坏主意——是Object.setPrototypeOf:

Object.setPrototypeOf(api, Person);

使用 Object.create 基于原型(prototype)创建对象然后向其添加属性的正常方法在这里工作得很好:

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

关于javascript - 相当于使用 __proto__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42032726/

相关文章:

javascript - 如何使用正则表达式进行 Angular 过滤

javascript - 用python下载网站供离线浏览

c++ - C++如何区分派(dispatch)生类的对象

c++ - 为什么我收到错误 C2061(语法错误 : identifier)?

javascript - 如何在 "return this"的揭示模块模式中处理本地函数

javascript - 立即调用 IIFE 如何防止它污染全局范围?

javascript - jasmine之前都受sibling describe的影响

javascript - 添加 jQuery .click() 到动态创建的 HTML

c++ - 为什么派生类不能访问基类静态方法?

javascript - 用 Angular 揭示模块模式