我对JavaScript的原型继承有很好的理解,但我不认为它是完美的。我正在研究JavaScript继承的最新原型语法,到目前为止,这是相当有意义的。
__proto__用于查找父函数的prototype。假设我有Cat和Mammal,我可以简单地将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;是不好的,因为修改儿童类的原型也会修改ParentClass的原型。
但为什么我们不能这么做?
ChildClass.prototype = new ParentClass();为什么我们需要一个代孕母亲?
发布于 2017-09-05 18:56:14
但为什么我们不能这么做?
ChildClass.prototype = new ParentClass();
如何知道调用ParentClass构造函数w/o参数不会引发错误?
假设ParentClass是以这种方式实现的。
function ParentClass(name) {
if(!name) throw new Error('name is required');
this.name = name;
}https://stackoverflow.com/questions/46061523
复制相似问题