Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype chaining, Constructor, Inheritance

Tags:

javascript

I'm playing with javascript prototype. I'm new to it so I've got a small question.

I'm using this article as a guide.

I've got a Product defined and a Book defined. what is the purpose of Book.prototype.constructor = Book(); this. I can't figure out. I'm able to call parent constructor with and without it both successfully.

Book.prototype = new Product;
Book.prototype.constructor = Book; // What's the purpose of this

Here's my jsFiddle link

like image 247
Headshota Avatar asked Apr 03 '11 11:04

Headshota


People also ask

What is prototype and prototype chaining?

Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

What is prototype and prototype inheritance?

Every object with its methods and properties contains an internal and hidden property known as [[Prototype]]. The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object.

Is prototype the same as inheritance?

In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype.

What is prototypal inheritance give example?

Here we can say that " animal is the prototype of rabbit " or " rabbit prototypically inherits from animal ". So if animal has a lot of useful properties and methods, then they become automatically available in rabbit . Such properties are called “inherited”.


1 Answers

First off, new Product() creates an object with all prototype variables of the Product function. So, by setting Book.prototype = new Product(), Book inherits all prototype variables of Product.

You might think you could also say: Book.prototype = Product.prototype, but that solution doesn't work as expected. The prototype of Book becomes a pointer to the prototype of Product, and therefore it's not a copy. If you would change something to the prototype of Book, it is actually changed in the prototype of Product, and that's not what you want.

Shortly, new Product() creates a copy of all prototype variables.


But there is a problem with this method too. If you would create a new Book now, the Product constructor is called, instead of the Book constructor. To solve that, you need to set the constructor correctly again, and it'll work:

Book.prototype.constructor = Book;
// Note: it's not Book(), but Book, it's a reference to the function
like image 68
Harmen Avatar answered Sep 19 '22 08:09

Harmen