为什么在 JavaScript ES5 原型继承中需要代理项 class?

Why was surrogate class needed in JavaScript ES5 prototypal inheritance?

我对JavaScript的原型继承有很好的理解,但我不会说它是完美的。我正在查看 JavaScript 继承的最新原型语法,到目前为止它很有意义。

__proto__用于查找父函数的prototype。假设我有 CatMammal,我可以简单地将 Cat.prototype.__proto__ 指向 Mammal.prototype

ChildClass.prototype.__proto__ = ParentClass.prototype;
ChildClass.prototype.constructor = ChildClass;

强烈建议不要使用 __proto__,因为它直到最近才被标准化。因此,现代标准化做法是使用 Object.create

ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;

现在让我们看看 ES5 的替代方法

function Surrogate() {};
Surrogate.prototype = ParentClass.prototype;
ChildClass.prototype = new Surrogate();
ChildClass.prototype.constructor = ChildClass;

显然,

ChildClass.prototype = ParentClass.prototype;

不好,因为修改ChildClass的原型也会修改ParentClass的原型。

但为什么我们不能这样做呢?

ChildClass.prototype = new ParentClass();

为什么我们之间需要一个代理人?

But why can't we do this?

ChildClass.prototype = new ParentClass();

你怎么知道调用 ParentClass 构造函数 w/o 参数不会引发错误?

想象一下 ParentClass 是这样实现的。

function ParentClass(name) {
  if(!name) throw new Error('name is required');

  this.name = name;
}