Reputation: 3323
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);
}
Upvotes: 0
Views: 141
Reputation: 664548
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);
Upvotes: 1
Reputation: 504
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
Upvotes: 1