I have an object called superCar. I have a function Car. I would like to inherit my Car Object from superCar Object. Here is my code:
var superCar = {
model : "sedan"
};
function Car(){
this.name = null;
}
var c1 = new Car();
c1.name="Toyota";
var c2 = new Car();
c2.name="Bmw";
console.log(c1.name);
console.log(c2.name);
c1.__proto__.__proto__ = superCar.__proto__ ;
console.log(c1.model);
I am expecting the out put will be "Toyota" , "Bmw" , "sedan". But the output is comming out as "Toyota" , "Bmw" , "undefined". Can any one of you please explain why my inheritance did not work?
You are mixing inheritance patterns up a bit. Your inheritance isn't working because model
isn't on the superCar
prototype chain, it's directly on the object itself.
You can make superCar
a function like car and tie it into the inheritance chain like:
function superCar(){
this.model = "sedan"
};
function Car(){
superCar.call(this) // this will add model and other properties assigned in the constructor
this.name = null;
}
Car.prototype = Object.create(superCar.prototype); // this will add protoype methods from superCar, but there aren't any
var c1 = new Car();
c1.name="Toyota";
var c2 = new Car();
c2.name="Bmw";
console.log(c1.name);
console.log(c2.name);
console.log(c1.model);
console.log(c2.model);
Alternatively you can use Object.create
to create a prototype-link to the object superCar
with something based on this:
let superCar ={
model: "sedan"
};
function Car(name){
let obj = Object.create(superCar) // obj will delegate to superCar when it doesn't find a property
obj.name = name
return obj
}
var c1 = Car("Toyota");
var c2 = Car("Bmw");
console.log(c1.name);
console.log(c2.name);
console.log(c1.model);
console.log(c2.model);
You might be able to do a mix of these two pattern, but it's going to be confusing.