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;
}
present() {
return "I have a " + this.carname + ".";
}
}
mycar = new Car("Toyota");
document.getElementById("demo").innerHTML = mycar.present(); // outputs "I have a Toyota."
Prototype Approach:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
//adding a new method to the prototype:
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
var john = new Person("John", "Doe", 43, "Blue");
console.log(john.name); // outputs "John Doe"
So, what is the difference between using a class vs. a prototype like below and when do you use either approach?
To answer your question simply, there is no real difference.
Straight from the MDN web docs definition:
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With