gpt4 book ai didi

javascript - 相当于使用 __proto__?

转载 作者:行者123 更新时间:2023-11-28 14:58:15 27 4
gpt4 key购买 nike

我正在尝试使用带有继承的揭示模块模式。我似乎让它工作正常,但它使用“__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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com