1

I have seen number of js libraries use both function constructor and class together, but cannot figure out why they do so.

Definitely, when using class constructor, if we need to support ES2015 browser, we need to use babel, which do a transpilation, and is definitely add more code to the exported js files. e.g.

class Person {
  constructor(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  } 
}

will transpile to

"use strict";

function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }

function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Person = function Person(name, age, gender) {
  _classCallCheck(this, Person);

  this.name = name;
  this.age = age;
  this.gender = gender;
};

which is definitely longer than

function Person(name, age, gender) {
   this.name = name;
   this.age = age;
   this.gender = gender;
}

This is definitely an advantage of using function constructor over class, if one need to support older browser. I would say this is a kind of optimization. But what if I do not care about the bundle size, after all, my project does not have many codes, and little more of code doesn't affect too much.

Moreover, using class, will raise error, when we are not trying to new it. As it is completely legal to write Person('John', 18, 'M') in functional constructor, but not in class. Not to mention, it is completely clearer to programmer who use the constructor, to know they need to new it, in order to use it.

So my question is,

What advantages do I have when I use function constructor over class?

CHANist
  • 1,302
  • 11
  • 36
  • `if we need to support ES2015 browser` then you wouldn't need to transpile that first snippet. – Patrick Roberts Dec 30 '19 at 08:42
  • Also `I have seen number of js libraries use both function constructor and class together` could you cite one such example? I'd be surprised to see any widely used libraries using code this inconsistent. – Patrick Roberts Dec 30 '19 at 08:43
  • When you call a functional constructor without the `new` keyword you won't be able to access class expressions, i.e `let person = Person('John', 18, 'M'); person instanceof Person // false` but `let person2 = new Person('Jane', 18, 'F'); person2 instanceof Person // true` – Attila Dec 30 '19 at 08:44
  • @PatrickRoberts matrix-react-sdk source code, see https://github.com/matrix-org/matrix-react-sdk. Most sources are using class, but some use function. Cannot figure it out. – CHANist Dec 30 '19 at 08:49
  • @PatrickRoberts, `VectorConferenceHandler.js` use functional constructor for example, and `KeyRequestHandler.js` use class constructor. – CHANist Dec 30 '19 at 09:09

0 Answers0