Encapsulation: Private and Public Methods

👋 Ciprian on Monday, January 15, 2018 in Blog, JavaScript
Last modified on Monday, January 8, 2018

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() {
    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.

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

👋 Added by Ciprian on Monday, January 15, 2018 in Blog, JavaScript. Last modified on Monday, January 8, 2018.

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy