EDIT: I figured it out from Bergi\'s answer in the end.
Thanks Bergi.
pubPrivExample = (function () {
return {
init : function () {
I think this is a clear way to achieve your requirements:
var personFactory = function(id, name, age){
var _id = id;
var _name = name;
var _age = age;
var personPrototype = {
getId: function(){
return _id;
},
setId: function(id){
_id = id;
},
getName: function(){
return _name;
},
setName: function(name){
_name = name;
},
getAge: function(){
return _age;
},
setAge: function(age){
_age = age;
},
work: function(){
document.write(this.toString());
},
toString: function(){
return "Id: " + _id + " - Name: " + _name + " - Age: " + _age;
}
};
return Object.create(personPrototype);
};
Usage:
var renato = personFactory(1, "Renato Gama", 25);
console.log(renato.getName()); //logs "Renato Gama"
renato.setName("Renato Mendonça da Gama");
console.log(renato.getName()); //logs "Renato Mendonça da Gama"
If I am not wrong this is one the MODULE PATTERN usages. Refer to this post for a nicer explanation. This is also a good post about the subject.