Wilhelm
Wilhelm

Reputation: 1437

Why is it necessary to use Object.create()

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?

Upvotes: 3

Views: 127

Answers (1)

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

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'

Upvotes: 3

Related Questions