简体   繁体   中英

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?

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.

There are several ways to have private variables:

I favor Symbols, though they can still be found using reflection (ie not completely private). Example:

var Person = (function() {
    var nameSymbol = Symbol('name');
​
    function Person(name) {
        this[nameSymbol] = name;
    }
​
    Person.prototype.getName = function() {
        return this[nameSymbol];
    };
​
    return Person;
}());

So it's possible to have (reasonably) private variables, but unfortunately none of the solutions are as elegant as you'd like.

as GoldenerAal mentioned, they are not called classes, but functions you have

var ItemManager = function (){
..
...
...

};

you could have:

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

function addItem(item){
...
};
};

you can then create an instance of ItemManager, only when you need to :

var itemManager = new ItemManager();
itemManager.addItem(<something here>);

http://javascript.crockford.com/private.html variables inside a function only have the scope of that function, that variable is not a global variable (static variable).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM