I understand that the latest version of JavaScript (ES6) now supports creating classes. I also understand that the usual way to create and work with objects in ES5 and earlier versions of JS was to create object prototypes. So, what is the difference between using a class vs. a prototype like below and when do you use either approach?:
Class Approach:
class Car {
constructor(brand) {
this.carname = brand;
}
printStatement() {
return "I have a " + this.carname + ".";
}
}
mycar = new Car("Toyota");
document.getElementById("demo").innerHTML = mycar.printStatement(); // outputs "I have a Toyota."
Prototype Approach:
function Person(firstName, lastName, age, eyecolor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyecolor;
}
//adding a new method to the prototype:
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
var john = new Person("John", "Doe", 43, "Blue");
console.log(john.fullName); // outputs "John Doe"