I’m relatively new to using oop in Javascript, and I’m wondering what the best practice is for private methods. Right now, I’m using mootools to create my classes and I’m simulating private methods by prefixing them with an underscore and forcing myself not to call the method outside of the class. So my class looks like:
var Notifier = new Class(
{
...
showMessage: function(message) { // public method
...
},
_setElementClass: function(class) { // private method
...
}
});
Is this a good/standard way to handle private methods in JS?
MooTools provides a
protectmethod on functions, so you can call protect on any method that you want to protect from being called outside theClass. So you can do:Not that
classis a future reserved keyword in JavaScript and your code may break when using it. It certainly breaks on Safari at this point, but the behavior in other browsers is not guaranteed as well, so it’s better to not useclassas an identifier at all.One advantage of using
protectover creating closures yourselves is that if you extend this class, you can still access the protected methods in subclasses.If you want to use a naming convention such as prefixing or suffixing
_before or after a method, then that’s perfectly fine as well. Or you can combine the_with the protected methods too.