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
2 Answers 2
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
Comments
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.
Object.createdoes, have a look at the MDN documentation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…