Code is from mozilla website
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.call(this, name, price);/// why not this be Product(name,price)
this.category = 'food';
}
Food.prototype = new Product();
may very silly thing, can't understand this line
Product.call(this, name, price);
Since both Product and Food are global functions why do we have to use Product.call
The Product function is a constructor, this would normally be called with new. Using new when calling a function creates a new empty object, and calls the function with the new object as the context, it also sets up the prototype chain.
In this example Food is sub-classing Product, it wants to run the Product constructor on the new instance of Food.
An example should make things clear:
var f = new Food ('apple', 10)
f.name = 'apple'
f.price = 10
f.category = 'food'
The name and price category is being added to the object by calling the Product constructor with the new instance of Food.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With