Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code use <function>.call()?

Tags:

javascript

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

like image 687
Sankara Avatar asked Feb 23 '26 01:02

Sankara


1 Answers

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.

like image 193
Oliver Nightingale Avatar answered Feb 25 '26 13:02

Oliver Nightingale