Encapsulation: Private Attribute

Ciprian on Monday, January 15, 2018 in Methods, Events and Scopes

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

In JavaScript OOP there are attributes called private attributes. Knowing if an attribute is private or public, an API user can focus on the API as a whole.

Let’s create some private attributes.

Note: See a guid() example function here.

(function() {
    let private_id = guid(); // This function should generate a unique UUID

    let init = function() {
        // Private attribute holder
        this[private_id] = {};

        // Create_time is a private attribute
        this[private_id].creation_time = (new Date()).getTime();

    // This is the public method accessing the private attribute
    let get_creation_time = function () {
        return this[private_id].creation_time;

    // Anything listed below are public methods
    My_Class = Class.extend({
        init: init,
        get_creation_time: get_creation_time

Related posts

Leave a Reply

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