1

I'm trying to understand chaining constructors with javascript's call function. I'm looking at an example from here.

I've copied and pasted the example:

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);
  this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}
Toy.prototype = Object.create(Product.prototype);

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

What I'm confused about is that the call function for Food and Toy is called in their "constructor", but the object is not created until we called Object.create(Product.prototype) a few lines down... or so I thought.

Where exactly is the object being inherited created here? And what exactly is happening when we do Product.call? Is it creating an instance of Product? How does that relate to Object.create(Product.prototype)?

Penguinator
  • 641
  • 3
  • 11
  • 22
  • 1
    Maybe the following answer will help clarify some things: http://stackoverflow.com/a/16063711/1641941 the answer given is good and correct, you can mark it so. – HMR Feb 10 '14 at 11:22

1 Answers1

0

The objects are being declared and instantiated in these two lines that call the constructor function:

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

Before they are instantiated the function constructors Food and Toy are declared and their prototypes are set to an instance of Product. This occurs in the following lines:

function Food(name, price) {/*omitted*/}
Food.prototype = Object.create(Product.prototype);

function Toy(name, price) {/*omitted*/}
Toy.prototype = Object.create(Product.prototype);

Regarding the calls to the parent constructor:

 Product.call(this, name, price);

This line will call the Product constructor assigning the Food or Toy instance to this in the call to the Product constructor while passing in the name and price arguments. If your familiar with Java this is slightly similar to calling the super() constructor in a derived class.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189