Friday, May 17, 2024
155
rated 0 times [  161] [ 6]  / answers: 1 / hits: 12821  / 5 Years ago, fri, september 13, 2019, 12:00:00

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"

More From » ecmascript-6

 Answers
6

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.



[#6259] Wednesday, September 11, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;