Ravi
Ravi

Reputation: 2558

JavaScript Prototypical Inheritance

I've some code like

function Vehicle(){
  this.isMovable = true;
}
Vehicle.prototype = {
  hasTyres:function(){ return true;},
  needsFuel:true
};

var Car  = function(){
  Vehicle.call(this);
  this.type = "Car";
};

Now

It works even if I create prototype like this

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

or

Car.prototype = Vehicle.prototype;

What is the difference ?

I was under the impression that

Car.prototype = Object.create(Vehicle); 

will cause Car to inherit from vehicle ,but it's not.

Can anyone explain what's happening inside Object.create method

Thanks, SRK

Upvotes: 0

Views: 58

Answers (2)

Joseph
Joseph

Reputation: 119827

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

This one creates an object whose prototype is Vehicle.prototype. In this object, you put your shared methods for Car instances while "inheriting" from Vehicle. This is the right way to go.

Car instance -> Car prototype -> Vehicle prototype

Car.prototype = Vehicle.prototype;

This one uses the same prototype for Vehicle to Car. This means that you'll be clobbering the same object for both classes. Adding to Car.prototype would mean also adding it to Vehicle.prototype, which you don't want.

Car instance -> Car prototype (which is also Vehicle prototype)

Car.prototype = Object.create(Vehicle);, Car.prototype is an object whose prototype is Vehicle, a function. You don't want this either.

Car instance -> Car prototype -> Vehicle function

Upvotes: 3

SLaks
SLaks

Reputation: 887275

Vehicle is a function. Calling Object.create(Vehicle); will create an object whose prototype is that function.
That's not what you want.

Writing Car.prototype = Vehicle.prototype; will use the same prototype object for both classes, making it impossible to add a function to the derived class only.

For more details, see my blog.

Upvotes: 1

Related Questions