A direct counterpart, which is not idiomatic to ES6 classes:
class MyClass {}
MyClass.prototype.value = (() => {
let privateVariable = 0;
return function() {
return ++privateVariable;
};
})();
There are no practical reasons to make privateVariable
completely unavailable from the outer scope, especially since it doesn't play well with ES6 classes. This cannot be considered a proper encapsulation because privateVariable
isn't available for reflection; it cannot act as protected member as well.
There can be private member that stores a value:
class MyClass {
constructor() {
this._value = 0;
}
value() {
return ++this._value;
}
}
It could be a symbol but this doesn't make class design more secure, just introduces additional complications when a class is inherited in another module:
// should be carried around everywhere to make the class extendable
export const VALUE = Symbol('value');
class MyClass {
constructor() {
this[VALUE] = 0;
}
value() {
return ++this[VALUE];
}
}
Note that get value() {}
is not same thing as value() {}
.
One of TypeScript (which is a superset of ECMAScript) benefits is the encapsulation that is enforced at compilation time.