ES6 Private Member Syntax

I have a quick question. What is the cleanest and easiest way to declare private members inside ES6 classes?

In other words, how to implement

function MyClass () { var privateFunction = function () { return 0; }; this.publicFunction = function () { return 1; }; } 

as

 class MyClass { // ??? publicFunction () { return 1; } } 
+6
source share
1 answer

This is not very different for classes. The body of a constructor function simply becomes the body of a constructor :

 class MyClass { constructor() { var privateFunction = function () { return 0; }; this.publicFunction = function () { return 1; }; } } 

Of course, publicFunction can also be a real method, as in your example, if it does not need access to privateFunction .

I do not particularly recommend this (I am against pseudo-private properties for various reasons), but that would be the easiest translation of your code.

+4
source

Source: https://habr.com/ru/post/987051/


All Articles