例如js代码为:
function Fruit() {this.type = "fruit";};
function Apple() {this.name = "apple"; this.__proto__ = new Fruit();}
如果我多次调用
new Apple()
,是否会生成相同数量的new Fruit()
?还是取决于实施?
不会的。
因为原型被所有对象共享。苹果的任何对象都会有一个类似于水果的原型,但每次都不会创建新的水果对象。
但是设置 _proto 是一种不好的做法。相反,你可以这样做
Apple.prototype=Object.create(Fruit.prototype)
两者确实有相同的效果。
供参考:原型参考.