MooTools provides a protect
method on functions, so you can call protect on any method that you want to protect from being called outside the Class
. So you can do:
var Notifier = new Class({
showMessage: function(message) {
},
setElementClass: function(klass) {
}.protect()
});
var notifier = new Notifier();
notifier.showMessage();
notifier.setElementClass();
> Uncaught Error: The method "setElementClass" cannot be called.
Not that class
is 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 use class
as an identifier at all.
One advantage of using protect
over creating closures yourselves is that if you extend this class, you can still access the protected methods in subclasses.
Notifier.Email = new Class({
Extends: Notifier,
sendEmail: function(recipient, message) {
// can call the protected method from inside the extended class
this.setElementClass('someClass');
}
});
var emailNotifier = new Notifier.Email();
emailNotifier.sendEmail("a", "b");
emailNotofier.setElementClass("someClass");
> Uncaught Error: The method "setElementClass" cannot be called.
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.