【发布时间】:2014-10-01 01:35:44
【问题描述】:
这是我的代码:
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0) throw RangeError('Invalid');
return this;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
var cheese = new Food('feta', 5);
当我在控制台中检查变量时,我看到以下内容:
Food {name: "feta", price: 5, category: "food"}
这是我所期望的。
但是,如果我省略 Object.create(Product.prototype),我会看到相同的结果,因为 Product.call。
Object.create(Product.prototype)继承是必要的,如果是,为什么?
【问题讨论】:
-
另见Benefits of using
Object.createfor inheritance。您没有看到任何区别,因为您没有向Product.prototype添加任何内容。
标签: javascript oop object inheritance prototype