Fun With Mootools Part 2: Protected Methods

P

rivate and protected class methods can come in handy when creating complex applications. While JavaScript doesn't provide these features natively, Mootools provides a mechanism to define protected methods on a class. Protected means that the function can only be called by the originating class or a sub-class of the originating class. An attempt to call a protected function by a different class or from an instance of the class would result in error. Here is how you do that with a mootools classs:

var SecretClass = new Class({  
    Implements:[Options]
    , initialize: function( options ){
        this.setOptions( options );
        var s = this.protectedMethod();
    }

    /**
     * A regular class method 
     */
    ,publicMethod: function( name ){
        alert("Hello" + ( name || "world") + "!");
    }

    /**
     * A protected class method
     */
    ,protectedMethod: function( val ){
        this.stuff = ["things", "words"];
        return this.stuff;
    }.protect() // this is protected!
});

///////  Create An Instance  //////
var S = new SecretClass();  
s.publicMethod( "Eric" )// alerts "Hello Eric!"  
s.protectedMethod() // Throws an error  

Notice the .protect() call on the end. Inside the initialize method calling protectedMethod is perfectly legal as the call is coming from the originating class. However, if we try to create an instance and call protectedMethod from that, we will get an error.

This can be especially helpful when designing classes that will be used by the public. You will be able to design a public and private API. Developers will always be able to open a javascript firebug or developer tools and see what method are on a class instance, but this is a simple way to ensure they aren't able to use them in ways they weren't intended for.

mootools class javascript oop