Encapsulation: Private and Public Methods

Ciprian on Monday, January 15, 2018 in jQuery

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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() {
    let my_private_method_1 = function (param_1) {
        console.log(this.settings.param1);
    };

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

    let 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
    });
})();

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

my_object.my_public_method_1();

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *