5

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.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37
  • The `class` declaration syntax doesn't really add new functionality to the language. You create getters and setters on the constructor's `prototype` object. Performance is not an issue. – Pointy Apr 07 '18 at 14:24
  • 1
    Yes, of course it is possible to put getter and setter properties, either on the instance or on the prototype object, with both syntaxes. – Bergi Apr 07 '18 at 14:25
  • 1
    This post contains multiple questions that are possibly very broad and/or opinion-based. Try and narrow down your question to a more specific topic. – Boaz Apr 07 '18 at 14:26
  • I just want to know the difference (if there is any) between constructor functions and **classes**, not using prototypes. – D. Pardal Apr 07 '18 at 14:32
  • @D.Pardal I don't understand how you can ignore `Thing.prototype`, it is always used in `new Thing`, both when you use an ES6 `class` or ES5 syntax to define `Thing`. – Bergi Apr 07 '18 at 15:14
  • @D.Pardal See also https://stackoverflow.com/q/310870/1048572 and the second duplicate link (about perf differences). You can use both syntaxes to assign properties to the instance and not use the prototype, but you should not (and in your `class` example, you didn't). – Bergi Apr 07 '18 at 15:16
  • *I'm not referring to using Thing.prototype* - but you should, because everything in ES6 class syntax except `constructor` body refers to class `prototype`. ES6 classes were designed to naturally extend built-ins, which is possible only via a hack otherwise. – Estus Flask Apr 07 '18 at 18:43

0 Answers0