在 JavaScript 中理解(误解?)基于原型的 类

Understanding (missunderstanding?) prototype based classes in JavaScript


我试图了解原型 class 系统在 JS 中的工作原理。到目前为止,我对创建和显示对象(在 Firefox 中)后得到的结果有点困惑。
当我使用 'Example 1' 创建一个对象时,我得到了一个对象,它的原型有一个 属性(说函数)并且有一个实例 属性 'type'。而且这种行为很明显。
但是在第二个示例中,使用关键字 'new' 我得到了一个带有实例 属性 'type' 的对象和一个本身具有构造函数(Rabbit)和定义函数 'speak' 的原型。并且此函数 'speak' 具有非空 'prototype' 属性 并且此关系更进一步等。与原型构造函数相同。他的构造函数 'prototype' 属性 持有与上一关等相同的内容
而这种行为看起来就像一棵无限递归树。我不明白这种行为是不是正常语言"feature"?

// Example 1
let protoRabbit = {
    speak(line) {
    console.log(`The ${this.type} rabbit says '${line}'`);
    }
};
function makeRabbit(type) {
    let rabbit = Object.create(protoRabbit);
    rabbit.type = type;
    return rabbit;
}
// Example 2
function Rabbit(type) {
    this.type = type;
}
Rabbit.prototype.speak = function(line) {
    console.log(`The ${this.type} rabbit says '${line}'`);
};
let weirdRabbit = new Rabbit("weird");
console.log(weirdRabbit);

它实际上不是 'infinite',即使它看起来像。 (Rabbit) 对象的原型构造函数会返回自身,因此随着您的深入,您只是一遍又一遍地打开同一个 (Rabbit) 对象。

构造函数原型隐式返回自身,以便其他子级可以通过“[[prototype]]”对象访问父级。我们可以使用构造函数 属性 使用与现有构造函数相同的构造函数创建一个新对象。

您可以从以下网站找到这方面的详细知识。

https://javascript.info/function-prototype