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?