0

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

asked Sep 28, 2014 at 2:55
2

2 Answers 2

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
answered Sep 28, 2014 at 3:00
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Sep 28, 2014 at 2:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.