I am working on trying to make an JS object and access to private methods. The problem I am running into when trying to return a function is the private methods cannot be accessed. Code Below.
var Item = (function() {
var price = 0;
var name = '';
var description = '';
var quantity = '';
var attributes = {};
var Item = function(data) {
}
function setPrice(variable) {
this.price = variable;
};
function getPrice() {
return this.price;
};
function setName(variable) {
this.name = variable;
};
function getName() {
return this.name;
};
function setDescription(variable) {
this.description = variable;
};
function setQuantity(variable) {
this.quanity = variable;
};
return function(data){
setPrice : setPrice;
getPrice : getPrice;
setName : setName;
setDescription : setDescription;
setQuantity : setQuantity;
return new Item(data);
}
})();
item2 = Item();
item2.setPrice('3');
alert(item2.getPrice());
With this setup, how can I access the private methods?
I don’t think that pattern will work for what you’re trying to do. I think using a pattern like this one will keep your code smaller and more reusable. This way you also get rid of the
setfunctions.