Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: When to use a Class vs. a prototype? [duplicate]

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"
like image 884
rajndev Avatar asked Sep 13 '19 19:09

rajndev


1 Answers

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.

like image 109
Nick Zuber Avatar answered Sep 18 '22 12:09

Nick Zuber