getButterfly
Resume

Encapsulation: Private and Public Methods

When it comes to developing APIs, self documenting code is very important, in order to simplify users’ effort in filtering the information they need. If it is clearly visible which parts are public and which parts are private, understanding the big picture of the API would be easier for the user.

We can use this JavaScript function encapsulation technique:

(function() {
    var my_private_method_1 = function(param_1) {
        console.log(this.settings.param1);
    };

    var init = function(settings) {
        // Constructor
        this.settings = $.extend(true, {}, settings);
    };

    var my_public_method_1 = function() {
        // This public method has the access to call private methods
        my_private_method_1.bind(this)();
    };

    // Anything listed below are public methods
    My_Class = Class.extend({
        init: init,
        my_public_method_1: my_public_method_1
    });
})();

var my_object = new My_Class({
    param1: 'abcdef'
});

my_object.my_public_method_1();

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.


Leave a Reply