0

Let's take this object:

var person = {
    _name: "John",
    name: function() {return _name}
}

In GUI,

myTextBox.value = person.name()

will return

"John"

But

myTextBox.value = person.name

will return

function() {return _name}

How can I force both syntax to return "John"? Could I use a closure (question I asked previously) somehow here?

Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487

3 Answers3

1

You can't!

  • You can't override javascript operators or keywords.
  • you really can't have one operator\keyword that does two different things in the same context!
gdoron
  • 147,333
  • 58
  • 291
  • 367
1

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:

  1. make a rule that you have to use the function to access the variable (yuck)
  2. 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"
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
  • Great article http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx thanks – user310291 Mar 19 '12 at 21:17
  • Will try your second syntax (by the way my getter may be more complex than that but anyhow even in that simple case I just want to learn if it's possible :)). If it does work it will be the answer. – user310291 Mar 19 '12 at 21:23
1

Ok, had a play and it looks like this is "possible" (At least in chrome) but its a bit of a dirty hack.

var person = {
   _name: "John",
   name: function() {return this._name;},
}
person.name.toString = function(){ return person._name; }

Which will result in both person.name and person.name() returning "John".

Carl
  • 1,816
  • 13
  • 17