This question has already been answered:

And not protected, which is usually called starting with the underscore this._play() , namely private ones, so that they are not available not only from the outside, but also to the classes of heirs, so that the name conflicts do not happen.

And preferably without using Symbol, as it is not supported everywhere.

It is clear that in ES6 it is, but in ES5 how to deal with it?

Reported as a duplicate by user194374, Alexey Shimansky , Grundy , VenZell , D-side July 18, '16 at 11:24 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    as an option

     function MyClass() { var self = this; self.one = 1; // private; self.two = 2; return { add: function(val) { return self.one + val; }, two: self.two } } var mc = new MyClass(); console.log(mc.add(mc.two)); 
    • if you remove self and instead simply make var one=1 and call without new - it will look much prettier - Grundy
    • phenomenally, why did I not write like that before? XD - Maxmaxmaximus

    And here it is (with what it can be done for 200 years):

    ES6:

     var say = Symbol() class Cat { constructor(){ this[say]() // call private } [say](){ alert('im private') } } 

    ES5:

     var say = Math.random() // like Symbol() function Cat(){ this[say]() // call private methods } Cat.prototype[say] = function(){ alert('im a private') } 

    An example of using ES6:

     var handlers = Symbol() class EventEmitter { constructor(){ this[handlers] = [] } on(handler){ this[handlers].push(handler) } emit(){ for(let handler of this[handlers]) handler() } } class Cat extends EventEmitter { } var q = new Cat() q.on // function q.emit // function q.handlers // undefined cuz PRIVATE ;) 

    And it is not necessary to learn the names of properties from the implementation of a class, such as the internal property of handlers, for fear of accidentally blocking them in the classes of heirs. I have been using private for 6 years now. And no problems with leaks. I do not understand people who say that there is no private javascript.

    Enjoy;)

    • And where is ES6 in your answer? При чем желательно без использования Symbol так как он поддерживается не везде ? - Alexey Shimansky
    • Let's continue the discussion in the chat . - Maxmaxmaximus