首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么在JavaScript ES5原型继承中需要代理类?

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

Stack Overflow用户
提问于 2017-09-05 18:49:20
回答 1查看 190关注 0票数 0

我对JavaScript的原型继承有很好的理解,但我不认为它是完美的。我正在研究JavaScript继承的最新原型语法,到目前为止,这是相当有意义的。

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

代码语言:javascript
复制
ChildClass.prototype.__proto__ = ParentClass.prototype;
ChildClass.prototype.constructor = ChildClass;

__proto__的使用受到强烈的劝阻,因为它直到最近才被标准化。因此,现代标准化实践就是使用Object.create

代码语言:javascript
复制
ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;

现在让我们来看看es5的代孕方法。

代码语言:javascript
复制
function Surrogate() {};
Surrogate.prototype = ParentClass.prototype;
ChildClass.prototype = new Surrogate();
ChildClass.prototype.constructor = ChildClass;

显然,

代码语言:javascript
复制
ChildClass.prototype = ParentClass.prototype;

是不好的,因为修改儿童类的原型也会修改ParentClass的原型。

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

代码语言:javascript
复制
ChildClass.prototype = new ParentClass();

为什么我们需要一个代孕母亲?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-05 18:56:14

但为什么我们不能这么做? ChildClass.prototype = new ParentClass();

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

假设ParentClass是以这种方式实现的。

代码语言:javascript
复制
function ParentClass(name) {
  if(!name) throw new Error('name is required');

  this.name = name;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46061523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档