Using .call() to call a super constructor?

Below it looks like call is being used to assign a context to the sub constructor Food. It passes two arguments to Product.

That’s the extent of what I know. I know the end result is that Food inherits everything from Product. But I don’t know why.

Is Product being invoked with the constructor calling keyword new behind the scenes? Or is this a normal function call except with context switching thanks to call ?

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

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

Hi Sean

This is a way to ‘fake’ object orientation you would get in languages like Java and C#, as follows:

You write code like this:

var lentil = new Food('lentils', 100)

This will cause the following to happen:

  1. Because of new a new object {} is created and passed as the this value to Food
  2. The Food function then passes this to Product using call - which means that inside Product the this refers to the new {} object, and it sets the name and price values on it.
  3. Control passed back into Food and it sets an additional property on it food.
  4. There is no return statement, so by default that new object, now with the name, price and category keys is returned and assigned to lentils.

The result is that the resulting object has properties set by both the functions.

1 Like