$40.95

Emulate class private members in JS

Ask a question+
5

I want to export a class but don’t want the user to see internal properties. In other words I want to have private members like it is called in other programming languages.
I went through this article, but it is still a TC39 candidate.

I am using Node v12.9.1 .

How can I emulate private member for JS calsses ?

Tigran 1.2K
add comment

1 Answer

5

If you want to use private members in javascript classes, you should all private variables and the functions in which they use them, write in the same scope, for example in the constructor:

class A {
    constructor() {
        // public properties
        this.public_1 = 'public_1'
        this.public_2 = 'public_2'

        // private properties
        let private_1 = 'private_1'
        let private_2 = 'private_2'

        // functions which can use private properties
        this.getPrivate1 = () => {
            return private_1
        }
        this.setPrivate1 = (value) => {
            private_1 = value
        }
    }
}


const obj = new A()

console.log(obj.getPrivate1()) // private_1

obj.setPrivate1('I am really private')

console.log(obj.getPrivate1()) // I am really private
add comment

Your Answer