Member-only story
How to convert class to function
Interview question: How to convert class to function
class Animal {
constructor(name){
this.name = name;
}
getName(){
return this.name;
}
}
1. Characteristics of the class
Before we convert, let’s first understand the main characteristics of a class.
1. Constructor function (constructor):
The class must contain a method named constructor, which is a special function used to initialize newly created object instances. Constructor functions are usually used to set properties of instances or perform other necessary initialization operations.
2. Method definition:
The methods of a class (including instance methods and static methods) are directly defined within the body of the class and do not need to be assigned through .prototype. Method definitions are in the form of concise function expressions and do not require the function keyword.
3. Inheritance and extends keywords:
Using the extends keyword can achieve single inheritance. A class can inherit from another base class, and the subclass automatically obtains all non-private properties and methods of the base class. It can also call the constructor function and methods of the parent class through the super keyword.
4. Static members: