In this example, we have shared Private properties in JavaScript ES6 classes. Private fields (and methods) are being implemented in the ECMA standard. You can start using them today with babel 7 and stage 3 preset.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Something { #property; constructor(){ this.#property = "test"; } #privateMethod() { return 'hello world'; } getPrivateMessage() { return this.#privateMethod(); } } const instance = new Something(); console.log(instance.property); //=> undefined console.log(instance.privateMethod); //=> undefined console.log(instance.getPrivateMessage()); //=> hello world |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.