简体   繁体   中英

How to make Constructor function to point to Super function prototype in ES5

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);
}

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM