Reputation: 5133
I'm trying to make it possible to inherit from this class:
function Vehicle(p) {
this.brand = p.brand || "";
this.model = p.model || "";
this.wheels = p.wheels || 0;
}
Vehicle.prototype.getBrand = function () {
return this.brand;
};
Vehicle.prototype.getModel = function () {
return this.model;
};
Vehicle.prototype.getWheels = function () {
return this.wheels;
};
var myVehicle = new Vehicle({
brand: "Mazda",
model: "RX7",
wheels: 4
});
console.log(myVehicle);
I tried doing it this way:
function Vehicle(p) {
this.brand = p.brand || "";
this.model = p.model || "";
this.wheels = p.wheels || 0;
}
Vehicle.prototype.getBrand = function () {
return this.brand;
};
Vehicle.prototype.getModel = function () {
return this.model;
};
Vehicle.prototype.getWheels = function () {
return this.wheels;
};
function Car (){}
Car.prototype = new Vehicle();
Car.prototype.getWheels = function() {
return 4;
};
var myCar = new Car({
brand: "Mazda",
model: "RX7"
});
console.log(myCar);
but it seems like it doesn't work:
> Uncaught TypeError: Cannot read property 'brand' of undefined
Could someone explain to me what's wrong? I guess it's not the write way to implement it but why?
Upvotes: 2
Views: 83
Reputation: 254906
In addition to what @elclanrs said:
function Car () {
Vehicle.apply(this, arguments);
}
var c = function() {};
c.prototype = Vehicle.prototype;
Car.prototype = new c();
Live demo: http://jsfiddle.net/x3K9b/1/
Upvotes: 4
Reputation: 94101
You need to call "super" in Car
:
function Car() {
Vehicle.apply(this, arguments);
}
Aside from that you could make p
optional by just assigning an empty object for example; that would get rid of the error. And finally point to the right constructor so:
function Vehicle(p) {
p = p || {}; //<=
this.brand = p.brand || "";
this.model = p.model || "";
this.wheels = p.wheels || 0;
}
//...
Car.prototype = new Vehicle();
Car.prototype.constructor = Car; //<=
Edit: Otherwise just use Object.create
:
Car.prototype = Object.create(Vehicle.prototype);
That takes care of assigning the constructor and everything.
Upvotes: 3