When comparing Class and Function in JavaScript, it's often said that Class is just syntax sugar. However, the distinction between the two does matter. The JS parser handles them differently by categorizing them into various AST nodes such as ClassDeclaration and ClassExpression, which are distinct node types in the resulting AST tree:
https://github.com/estree/estree/blob/master/es2015.md#classes
The introduction of new AST elements with the ES6 Classes spec like ClassBody, MethodDefinition, ClassDeclaration, ClassExpression, and MetaProperty signifies a shift in syntax:
- ClassBody
- MethodDefinition
- ClassDeclaration
- ClassExpression
- MetaProperty
This variation in AST syntax can lead to different interpretations by the JavaScript engine when encountering Class or Function declarations.
The limitation lies in the fact that Class and Function declarations cannot be used interchangeably. This is evident when attempting to do something like:
class notWorking {
return 1; // <-- creates a parser error
};
Herein lies a small problem - achieving private variables within Class declarations becomes more complex compared to using Function declarations:
function myClass() {
var privateVar;
}
Unlike functions, only methods can be declared within the body of a Class declaration:
class myClass {
var privateVar; // ERROR: should be a method
}
A proposed solution for creating private fields in the future involves syntax like:
class myClass {
#privateVar; // maybe this works in the future?
}
Alternative approaches such as using Symbols for private properties have also been suggested:
Private properties in JavaScript ES6 classes
var property = Symbol();
class Something {
constructor(){
this[property] = "test";
}
}
Further distinctions between classes and functions include issues like Hoisting and special keywords unique to each, such as constructor and super in Classes. These nuances contribute to a clearer expression of objects in an OOP manner through the ES6 Class syntax.
Additional differences, considerations, and limitations between classes and functions can be explored here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes