1

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

Ravi
  • 2,470
  • 3
  • 26
  • 32
  • 2
    If you want to know what `Object.create` does, have a look at the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create – Felix Kling Sep 28 '14 at 03:00
  • A car is a vehicle but a vehicle is not necessarily a car (can be a bus). So you can't set their prototypes to be equal to each other. More on prototype here. http://stackoverflow.com/a/16063711/1641941 – HMR Sep 28 '14 at 03:30

2 Answers2

3

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
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964