javascriptoopinheritance

JavaScript - how to make it possible to inherit


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 doesn't work:

> Uncaught TypeError: Cannot read property 'brand' of undefined 

Could someone explain to me what's wrong? I guess this is not the right way to implement it, but why?


Solution

  • 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/