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

时间:2017-09-05 18:49:21

标签: javascript ecmascript-5 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();

为什么我们需要代理?

1 个答案:

答案 0 :(得分:1)

  

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

     

ChildClass.prototype = new ParentClass();

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

想象一下ParentClass以这种方式实现。

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

  this.name = name;
}