在Mozilla Dev Network上使用Function.Prototype.call示例:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
为什么传递对象文字而不是参数数组时,示例是否有效?该示例应为Product原型指定名称和价格,并返回带有相应名称和价格字段的Food和Toy对象,但结果将返回undefined。
function Product(data) {
this.name = data.name;
this.price = data.price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(data) {
Product.call(this,data);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(data) {
Product.call(this,data);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food({ name: 'feta', price: 5 });
var fun = new Toy({ name: 'robot', price: 40 });
console.log(cheese);
console.log(fun);
在Chrome中我得到了一个未被捕获的TypeError:无法读取属性&#39; name&#39;未定义的&#39; call函数传递对Product的引用后出错。
答案 0 :(得分:0)
问题在于:
Food.prototype = new Product();
// ...
Toy.prototype = new Product();
你在不传递参数的情况下调用Product
。您应该使用Object.create
代替。
Foo.prototype = Object.create(Product.prototype);
// ...
Toy.prototype = Object.create(Product.prototype);
这使您可以创建一个继承自另一个对象(在本例中为Product.prototype
)的对象,而无需调用构造函数。
另外,这个:
if (price < 0)
应该是这样的:
if (this.price < 0)