Equivalent JavaScript Class in Function
js/convert-class-to-function
Classes are a template for creating objects, built on prototypes. A JavaScript class is a type of function. So you can convert a class to a function.
1// <<< using class syntax >>>
2class Person {
3    constructor(name) {
4        this.name = name;
5    }
6
7    say() {
8        console.log(`Hello, ${this.name}`);
9    }
10}
11
12// <<< using function syntax >>>
13'use strict'; // class syntax is strict mode by default
14
15// call new on function is equivalent to create an object with the function as constructor
16function Person(name) {
17    // constructor cannot be called without 'new'
18    if (!(this instanceof Person)) {
19        throw new TypeError("Class constructor Person cannot be invoked without 'new'");
20    }
21    
22    this.name = name;
23}
24
25// class function is not enumerable by default,
26// so we need to set enumerable to false.
27Object.defineProperty(Person.prototype, 'say', {
28    value: function() {
29        // this must be an 'instance' of Person
30        if (!(this instanceof Person)) {
31            throw new TypeError("function say is not a constructor");
32        }
33        
34        console.log(`Hello, ${this.name}`);
35    },
36    enumerable: false,
37});
Unauthorized reproduction of original content on this website is prohibited.