If you support only modern browsers you can use a ES5 Getters, but in general this is JavaScript, why are you trying to make it complicated?
Your alternatives are:
- make a rule that you have to use the function to access the variable (yuck)
- don't worry about it.
I'd go for #2.
I think you're getting confused with this syntax here, but actually it has the same problem as you do now:
function Person(name) {
this._name = name;
}
Person.prototype.name = function(name) {
if (name) this._name = name;
return this._name;
}
var j = new Person("Jay");
j.name() // "Jay"
j.name("Thomas"); // I can set the value as well
j.name() // "Thomas"
It seems like you're trying to create real private variables, which are possible, but probably not that helpful.
function Person(name) {
var myName = name; // private
this.name = function() {
return myName;
}
}
var j = new Person("Jay");
j.name(); // still had to use perens
Finally because yours is just a simple object, we can do this. Not sure why you'd want to though:
var person = {};
(function(name) {
var myName = name; // myName and name, both private, but not helpful
person = {
name = myName
}
}("Jay"))
person.name // "Jay"