Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Class Best Practice?

I'm currently looking into different patterns for building classes in JavaScript. But no matther what pattern I see, there are still some things I am not really sure about.

var ItemManager = (function()
{
    var p = function()
    {
        this.items= [];
    };

    p.prototype.addItem = function(item)
    {
        var self = this;    
        self.items.push(item);
    };

    return p;
}());

I create the simple class ItemManager, this class got the function addItem for adding any item to the collection. Now I don't really want the variable items, which represents the collection, to be public, this variable should be private, but I don't see any possible way to use a prototyped method to access private variables.

So what's the best practice in this case? Simply don't use private variables?

like image 257
GoldenerAal Avatar asked Nov 01 '13 11:11

GoldenerAal


People also ask

Is it good practice to use classes in JavaScript?

In JavaScript, you don't! You can write any program you want without utilizing classes or the this keyword ever! Indeed, the class syntax is somewhat new to JavaScript, and object oriented code was written with functions beforehand. The class syntax is just syntactic sugar over that function-based approach to OOP.

Does a JS class need a constructor?

Simple example no error if you don't use a constructor in the class. Constructors require the use of the new operator to create a new instance, as such invoking a class without the new operator results in an error, as it's required for the class constructor to create a new instance.

What are JavaScript classes used for?

Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.

How many constructors can a class have in JavaScript?

Definition and Usage Note: A class cannot have more than one constructor() method.


1 Answers

var ItemManager = function() {
    var items = [];

    return {
           addItem : function(item) {   
               items.push(item);
           },
           removeItem : function() {
                return items.pop();
           }
     }
};

var myItemManager = new ItemManager();

items variable becomes hidden after the execution of ItemManager function, but addItem and removeItem still share the access to items. See the Douglas Crockford's article on private variables in JavaScript for further investigation.

like image 198
aga Avatar answered Sep 19 '22 05:09

aga