3

Here is my code:

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);

When I check the variable in my console, I see the following:
Food {name: "feta", price: 5, category: "food"}

Which is what I had expected.

However, if I omit Object.create(Product.prototype) I see the same results because of Product.call.

That said, what would be best practice in this case? Is Object.create(Product.prototype) even necessary for inheritance and if so, why?
Wilhelm
  • 1,407
  • 5
  • 16
  • 32
  • 2
    [This is a good explanation of what's going on.](http://stackoverflow.com/questions/11661078/javascript-oop-instanceof-and-base-class/11669057#11669057) – Pointy Aug 07 '14 at 17:45
  • See also [Benefits of using `Object.create` for inheritance](http://stackoverflow.com/q/17392857/218196). You don't see any difference because you didn't add anything to `Product.prototype`. – Felix Kling Aug 07 '14 at 18:05

1 Answers1

3

This line

Product.call(this, name, price);

gives the same effect as

this.name = name; //argument name from the function constructor
this.price = price; //likewise, argument of function constructor

but it does nothing to set the prototype property of the Food object. With this line

Food.prototype = Object.create(Product.prototype);

it ensures if a property of the Food object is looked up and JavaScript cannot find, it will follow the prototype chain to Product.prototype

Let's elaborate your example

function Product(name, price) {
   this.name = name;
   this.price = price;

   if (price < 0) throw RangeError('Invalid');
      return this;
}

and add a function to calculate the tax

Product.prototype.calculateTax = function() {
    return this.price * 0.1;
}

Now with this line

Food.prototype = Object.create(Product.prototype);

the following will calculate the tax correctly

var cheese = new Food('feta', 5);
console.log(cheese.calculateTax());

Omitting that line

//Food.prototype = Object.create(Product.prototype);

it will gives the error TypeError: Object # has no method 'calculateTax'

Kevin Le - Khnle
  • 10,579
  • 11
  • 54
  • 80