0

In ES5, I can write it like this:

MyClass.prototype.value = (function() {
    var privateVariable = 0;
    return function() {
        return ++privateVariable;
    };
})();

But in ES6, how can I do it ?

class MyClass {
    get value() {
        // return ??
    }
}
user2331095
  • 6,577
  • 8
  • 36
  • 56
  • Possible duplicate of [Private properties in JavaScript ES6 classes](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes) – Estus Flask Jul 03 '18 at 12:03

2 Answers2

1

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • In fact, I want to write a function like this: https://github.com/mrdoob/three.js/blob/master/src/core/Object3D.js#L195-L205. – user2331095 Jul 03 '18 at 14:17
  • 1
    @user2331095 You can write it the way you like. I'm just saying that it's not idiomatic and you won't see this in well-written ES6 OO code, because this approach doesn't have obvious advantages, while, on the contrary, the disadvantages are obvious. A lot of good coding habits tend to become obsolete. – Estus Flask Jul 03 '18 at 14:29
1

The equivalent to the ES5

function MyClass() {}
var privateVariable = 0;
MyClass.prototype = {
    get value() {
        return ++privateVariable;
    }
};

in ES6 class syntax would be

let privateVariable = 0;
class MyClass {
    get value() {
        return ++privateVariable;
    }
}

Whether you put all that in an IEFE or module or whatnot for local scope doesn't matter, it's the same.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375