Reputation: 91
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?
Upvotes: 6
Views: 5542
Reputation: 13993
There are several ways to have private variables:
I favor Symbols, though they can still be found using reflection (i.e. 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.
Upvotes: 1
Reputation: 29416
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.
Upvotes: 6
Reputation: 371
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).
Upvotes: -1