Skip to content

Instantly share code, notes, and snippets.

@willmtemple
Created May 9, 2022 17:57
Show Gist options
  • Save willmtemple/c03af3b58de6fa448a2b010d077a4637 to your computer and use it in GitHub Desktop.
Save willmtemple/c03af3b58de6fa448a2b010d077a4637 to your computer and use it in GitHub Desktop.
Old-style Inheritance
declare class Vehicle {
engines: number;
ignition(): void;
drive(): void;
}
declare class Car extends Vehicle {
wheels: number;
}
// "Traditional JS Class" `Vehicle`
function Vehicle(this: Vehicle) {
this.engines = 1;
}
Vehicle.prototype.ignition = function() {
console.log( "Turning on my engine." );
};
Vehicle.prototype.drive = function() {
this.ignition();
console.log( "Steering and moving forward!" );
};
// Natural inheritance??
function Car(this: Car) {
// More or less equivalent to super()
Vehicle.call(this);
// now, let's modify our `car` to specialize it
this.wheels = 4;
// override `Vehicle::drive()`
this.drive = function() {
Vehicle.prototype.drive.call( this );
console.log( "Rolling on all " + this.wheels + " wheels!" );
};
}
Car.prototype = Vehicle.prototype as Car;
var myCar = new Car();
myCar.drive();
// Turning on my engine.
// Steering and moving forward!
// Rolling on all 4 wheels!
@witemple-msft
Copy link

declare class Vehicle {
    engines: number;
    ignition(): void;
    drive(): void;
}

declare class Car extends Vehicle {
    wheels: number;
}

// "Traditional JS Class" `Vehicle`
function Vehicle(this: Vehicle) {
	this.engines = 1;
}
Vehicle.prototype.ignition = function() {
	console.log( "Turning on my engine." );
};
Vehicle.prototype.drive = function() {
	this.ignition();
	console.log( "Steering and moving forward!" );
};

// Natural inheritance??
function Car(this: Car) {
  // More or less equivalent to super()
  Vehicle.call(this);

	// now, let's modify our `car` to specialize it
	this.wheels = 4;
}

Car.prototype.drive = function() {
	Vehicle.prototype.drive.call( this );
	console.log( "Rolling on all " + this.wheels + " wheels!" );
};
Object.setPrototypeOf(Car.prototype, Vehicle.prototype as Car);

var myCar = new Car();

myCar.drive();
// Turning on my engine.
// Steering and moving forward!
// Rolling on all 4 wheels!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment