0

My question title may look completely confusing, which reflects my current state of mind :P

I was re-visiting basics of JavaScript Inheritance world. Following example should tell what i was trying to :

function Vehicle(engType, wheels, color){
    this._engType = engType;
    this._wheels = wheels;
    this._color = color;
}

var VP = Vehicle.prototype;

VP.setEngType = function(engType){
    this._engType = engType;
}

VP.setWheels = function(wheels){
    this._wheels = wheels;
}

VP.setColor = function(color){
    this._color = color;
}


function Car(cc, gears){
    this._cc = cc;
    this._gears = gears;
}


Car.prototype = new Vehicle();

Vehicle is super-type with its own set of properties and Car with its own which is sub-type of Vehicle.

All is good till here but once i create instance of Car and want to set other properties of its parent say engType / wheels / color i need to use Set accessor methods which is an overhead. Is there any way of doing it right away in Car (Sub-Type) constructor function. Like :

function Car(cc, gears, engType, wheels, color){
    this._cc = cc;
    this._gears = gears;

    // Setting super type props
    this.setEngType(engType);
    this.setWheels(wheels);
    this.setColor(color);
}
BeingSuman
  • 3,015
  • 7
  • 30
  • 48

2 Answers2

1

You can call like this,

function Car(cc, gears, engType, wheels, color){
    Vehicle.call(this,engType,wheels,color);
    this._cc = cc;
    this._gears = gears;    
}

Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;

For further details,refer to this website

sudharsan tk
  • 494
  • 6
  • 14
1

You want to call the parent constructor on the new instance (this) to do that initialisation:

function Car(cc, gears, engType, wheels, color) {
    Vehicle.call(this, engType, wheels, color);
    this._cc = cc;
    this._gears = gears;
}

And don't use a new call to create prototype:

Car.prototype = Object.create(VP);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375