I'm looking for the best way to write object-oriented (O-O) JavaScript (JS) code for a project I'm working on. My project assumes the latest version of Google Chrome so I have the possibility of using ECMAScript 6's (ES6) features.
While researching O-O JS, I came across the revealing module pattern, which strikes me as a clean way of writing O-O code in a language that does not have proper classes like in Java, for example.
Is there any reason to prefer using ES6 classes?
Please correct me if I'm wrong about this but ES6 classes appear to have the following irredeemable disadvantages:
- They make public class variables complicated.
- They make private class variables complicated.
- They create aesthetically ugly code.
- They need to be declared before creating a class instance.
As I hope my example below demonstrates, the revealing module pattern has none of these problems.
var revealingModulePattern = RevealingModulePattern("Revealing Module Pattern");
revealingModulePattern.publicMethodGetName(); // "Revealing Module Pattern"
revealingModulePattern._privateName; // Undefined
revealingModulePattern.publicMessage; // "Hello StackOverflow"
revealingModulePattern.publicMessage = "New message";
revealingModulePattern.publicMessage; // "New message"
function RevealingModulePattern(constructorArg)
{
var _privateName = constructorArg;
var publicMessage = "Hello StackOverflow";
function publicMethodGetName() {
return _privateName;
}
return {
publicMethodGetName: publicMethodGetName,
publicMessage: publicMessage
};
}
/***************************************************************/
var _privateName = Symbol();
class ES6Class
{
constructor(constructorArg) {
this[_privateName] = constructorArg;
}
get name() {
return this[_privateName];
}
}
var es6Class = new ES6Class("ES6 Class");
es6Class[_privateName]; // "ES6 Class"
es6Class.name; // "ES6 Class"
es6Class[_privateName] = "New 'private' name";
es6Class.name; // "New 'private' name"
es6Class.publicMessage = "Hello StackOverflow";
es6Class.publicMessage; // "Hello StackOverflow"
es6Class.publicMessage = "New message";
es6Class.publicMessage; // "New message"