So I'm planing to build a small library, but this question has a variety of applications.
I want to know the difference between using Constructor Functions and Classes to create objects. For example, both this code...
function Thing (name) {
this.name = name;
this.doSomething = function (){};
alert("A new thing was created.");
}
var x = new Thing();
... and this code ...
class Thing {
constructor(name) {
this.name = name;
alert("A new thing was created.");
}
doSomething() {}
}
var x = new Thing();
... produce the same result, but in different ways.
However, I'm more familiarized with constructor functions but I need to create objects with getters and setters. Even though MDN defines classes as "syntactical sugar", I don't know if it is possible to define getters and setters with constructors.
Also, witch is the best in terms of performance?
Note: I'm not referring to using Thing.prototype
. I want to know the difference between constructor functions and classes.