How to use Private Methods in JS?

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. 😏

Js class private method and field


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 👋!



I hope I was able to introduce you with something that you didn't know!

😃 Did you know about it before? Let's see how many of you were actually aware of this feature!

Comment below 👇

That's it for today 😇. Thanks for reading! Follow my blog to get more such small posts daily!



Comments