Christian
Christian

Reputation: 6440

JavaScript inheritance: why copy from an instance?

In JavaScript, when I want to inherit the properties from a "class", I write:

Car.prototype = new Vehicle();

Why do I assign an instance of vehicle here?

Why don't we write Car.prototype = Vehicle; or Car.prototype = Vehicle.prototype; instead? Why copy from an instance?

Upvotes: 2

Views: 60

Answers (2)

Vladimir Kurijov
Vladimir Kurijov

Reputation: 382

Basically .prototype is an object. And by making direct assignment

Car.prototype = Vehicle.prototype

you are copying object over a reference.

And if you try to modify Car.prototype in order to add new features, like making bip sounds, you will modify Vehicle.prototype too since they are both referencing the same object.

And that is not what you probably want.

Upvotes: 0

Pointy
Pointy

Reputation: 413846

First, you should really do

Car.prototype = Object.create(Vehicle.prototype);

The reasons are involved, but suffice to say that that's a better way to get a new object for your Car prototype and ensure that it inherits from the Vehicle prototype.

Now, the reason you want a new object for the Car prototype is that if you're bothering to make a subclass you'll probably want specialized behaviors that do apply to the subclass but don't apply to the more general parent class. You need a new object for those new properties; otherwise, you'd be adding those behavior properties to the Vehicle prototype, and all Vehicles would have access.

Finally, setting Car.prototype to just Vehicle doesn't make much sense. That would work, in that it would not cause an exception, but it would set the Car prototype to be the Vehicle constructor function itself.

Upvotes: 4

Related Questions