C
C
Cat Scientist2016-03-10 20:42:21
JavaScript
Cat Scientist, 2016-03-10 20:42:21

Es6 encapsulation missing?

Previously, I declared private properties and methods like this:

function MyClass () {
  var privateProperty = 'value';
  var privateMethod = function () {
    console.log ('Hi, I am privateMethod');
  };

  this.publicMethod = function () {
    privateMethod ();
    return privateProperty;
  };
}

And now I was so happy and started writing in Es6:
class MyClass {
  constructor () {
    // F**k yeah, я использую Es6... Как нет приватных свойств? o.O

    var privateProperty = 'value';
    var privateMethod = function () {
      console.log ('Hi, I am privateMethod');
    };

    // Нет-нет, постойте, какого ...?
  }
}

Actually, classes are a simplified syntax, the support of which does not matter if I want to use encapsulation? Or am I missing something?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-03-10
Protko @Fesor

Previously, I declared private properties and methods like this:

Previously, you created objects crookedly and you got a crooked implementation of the "module" pattern. Yes, and your "properties and methods" are private, they are, as it were, not quite properties and methods, they are just variables (static properties in terms of java) and functions.
Encapsulation in javascript is and has been achieved in the past through modules (hiding variables in a child scope.
let privateStaticVar = 'foo';

// то что экспортируется - то публичное
export default class MyClass() {
    constructor() {
    }
}

// или

export default (function () {
    let foo = 'foo';

    return class FooBar {
         constructor() {
         }
    };
}());

Well, symbols were added to es2015 as an easy option to make real private variables, well, there is also a weakmap.
const privateFoo = Symbol('foo');

export default FooBar {
    constructor(foo) {
       this[privateFoo] = foo;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question