Encapsulation: Private and Public Methods

on in jQuery
Last modified on

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