I've recently started learning Javascript and trying to wrap my head around few important concepts. As per my understanding till now, Javascript does not have classes, it uses constructor functions instead of classes to create blueprint for the objects. Example:
// javascript code
var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
// typescript code
class Car {
public speed: number = 10;
public acceleration(accelerationNumber: number): void {
this.speed += accelerationNumber;
}
public decelerate(decelerateNumber: number): void {
this.speed += decelerateNumber;
}
public getSpeed(): number {
return this.speed;
}
}
The above Typescript code makes much more sense because we have a class that creates a blueprint for that class objects. But, in Javascript this blueprint is being created with a function. So does that mean constructor function in Javascript does the same thing that classes does in Typescript/Java/etc.?
prototypeto define the methods and putspeedonthis.speed.