Using the Function.Prototype.call example on the Mozilla Dev Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
Why doesn't the example work when passing in an object literal instead of an argument array? The example should assign name and price to the Product prototype and return a Food and Toy object with the corresponding name and price fields, but the results come back 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);
In chrome I get a 'Uncaught TypeError: Cannot read property 'name' of undefined' error after the call function has passed reference to the Product.