Equivalent JavaScript Class in Functionjs/convert-class-to-functionClasses 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});Disclaimer
The code snippet is provided for reference and learning purposes only. Users should use it at their own risk. I, along with the related developers, shall not be held responsible for any direct or indirect losses caused by the use of this code snippet, including but not limited to data loss, computer malfunctions, program errors, etc.