That's kind of confusion is for adding so much "sugar" to our classes without to know what it is happening.
Your class is defined using ES6
class Car {
drive(speed) {
console.log('Drive at ' + speed)
}
}
Next what you do is construct an object using your class, using new
The first question is what the new keyword does?
- A new object is created, and this inherits from
Car
prototype
- This is attached to this newly created object
So, by doing const car1 = new Car();
, you get a new object wherein its prototype you get the drive
function.
In ES5 your class is written by using a constructor function.
function Car() {}
Car.prototype.drive = function (speed) { console.log(speed); }
Now, you can do: console.log(Car.prototype.constructor);
and you will see that the constructor function shown is Car.
If you want to create a subclass in ES6 you use the extends keyword but in ES5 what is really happening is:
Function SuperFastCar() {}
SuperFastCar.prototype = Object.create(Car.prototype);
SuperFastCar.prototype.turbo = function (maxSpeed) { console.log(maxSpeed); }
SuperFastCar.prototype.constructor = SuperFastCar;
Object.create
creates a new object using as the prototype the provided object. Also, we need to overwrite the constructor
, if not Car
constructor function will appear for SuperFastCar
.