If you are a programmer, you must have worked with Classes in different languages.
For example, in Java, security is a great advantage. You can't access whatever method you want in a Class. 😏
While coding in JS, you may have felt the lack of such feature. You can't declare private or public methods inside Classes.
Well, it's time to upgrade! With ES12, You can now declare Private Methods!
🤔 How to declare Private Method inside Classes?
💯 In the JS style!
It's as simple as a # prefix. Just like below -
class SpecialClass {
static #mySecretMethod() {
return 'little secret :P'
}
}
🥳 That's it! Now the method isn't public and can be used as a private stuff.
And... yes. You can also declare private fields with #. 👇
class ClassWithPrivateField {
#privateField
constructor() {
this.#privateField = 10
}
}
Remember⚠️, you can't delete declared fields. That will throw an Error.
Read More: ES12 Feature you should start using right now!
If you want to learn more about this new feature, go ahead and check this documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_With_Private_Class_Features
Conclusion 👋!
Comments
Post a Comment