【问题标题】:Why was surrogate class needed in JavaScript ES5 prototypal inheritance? [duplicate]为什么 JavaScript ES5 原型继承中需要代理类? [复制]
【发布时间】:2018-02-14 03:16:15
【问题描述】:

我对 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();

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

【问题讨论】:

  • 我个人认为您的ES5's surrogate approach 并不完全准确。 Object.create 在 2011 年被添加到 5.1 中,所以就现代 JS 而言,它已经存在了很长时间。
  • new 被使用之前 ES5 引入Object.create

标签: javascript ecmascript-5 prototypal-inheritance


【解决方案1】:

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

ChildClass.prototype = new ParentClass();

你怎么知道调用ParentClass不带参数的构造函数不会抛出错误?

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

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

  this.name = name;
}

【讨论】:

  • 啊谢谢,好点子!这是做代理课程的唯一原因吗?是否还有其他我应该注意的隐藏警告,并且该代理技巧旨在捕捉?
  • @cfeng ParentClass 可以做的任何其他副作用。例如,它可能会调用外部 API、递增计数器等。
  • @cfeng 我们根本不想调用构造函数。它应该初始化什么?周围没有实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多