Why 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"}

This is what I expected.

However, if I omit Object.create(Product.prototype)

, I see the same results from behind Product.call

.

However, what would be the best practice in this case? Is it Object.create(Product.prototype)

even necessary for inheritance, and if so, why?
+3


source to share


1 answer


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 that if a property of the Food object is looked up and JavaScript cannot find it, it will follow the prototype chain in Product.prototype

Tell 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 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 this line

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

      

it will throw TypeError: Object # has no method 'calculateTax'

+3


source







All Articles