在 JS 中定义继承链 - 为什么要重新创建原型? [英] Defining inheritance chain in JS - why recreate prototype?

查看:61
本文介绍了在 JS 中定义继承链 - 为什么要重新创建原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 https://developer.mozilla 时.org/en-US/docs/Learn/JavaScript/Objects/Inheritance 我看到我们应该用一个新的替换 Teacher 的原型,它的原型设置为 :

While reading through https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance I saw that we should replace the Teacher's prototype with a new one, which has its prototype set to Person:

Teacher.prototype = Object.create(Person.prototype);
Object.defineProperty(Teacher.prototype, 'constructor', { 
    value: Teacher, 
    enumerable: false, // so that it does not appear in 'for in' loop
    writable: true });

我宁愿这样做,对我来说似乎更合乎逻辑:

I'd rather do it this way, it seems more logical to me:

Teacher.prototype.__proto__ = Person.prototype

据我所知,它最终得到相同的结果并且构造函数保持正确,我不必替换它.

As far as I understand, it ends up with the same result and the constructor stays correct, I do not have to replace it.

MDN 的方法和我的有什么不同吗?

Is there any difference between MDN's approach and mine?

//编辑正如@Asutosh 指出的,MDN 不鼓励使用 __proto__ (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto).然而,MDN 也说使用 Object.setPrototypeOf 代替.那么,我可以这样做吗:

//EDIT As @ Asutosh pointed out, MDN discourages from using __proto__ (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto). However, MDN also says to use Object.setPrototypeOf instead. So, can I do this:

Object.setPrototypeOf(Teacher, Person.prototype)

代替原版

Teacher.prototype = Object.create(Person.prototype);
Object.defineProperty(Teacher.prototype, 'constructor', { 
    value: Teacher, 
    enumerable: false, // so that it does not appear in 'for in' loop
    writable: true });

推荐答案

我可以只做Object.setPrototypeOf(Teacher, Person.prototype)吗?

不,应该是

Object.setPrototypeOf(Teacher.prototype, Person.prototype);

你能用吗?是的,完全没问题,基本上等同于 Object.create + .constructor 定义.

Can you use that? Yes, it's totally fine, and basically equivalent to the Object.create + .constructor definition.

那为什么这不是标准方法呢?主要是因为 Object.create 从 ES5 开始可用,而 Object.setPrototypeOf 只在 ES6 中引入,但在 ES6 中我们只会使用 class Teacher extends Person无论如何.

So why is this not the standard approach? Mostly because Object.create was available since ES5, and Object.setPrototypeOf only was introduced with ES6, but in ES6 we would just use class Teacher extends Person anyway.

这篇关于在 JS 中定义继承链 - 为什么要重新创建原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆