0

As far as I understand the following statements are equal

  • object.property
  • object["property"]

So, I've been doing some testing and I can't figure out how to make dot notation work correctly for functionP.

I normally use a dump tool screendump somewhere on this page to see what's going on, but it doesn't show the properties for a function it seems.

Why can I do this

alert(functionE());     // returns key and date
alert(functionE.keyE);  // returns key and date

function functionE()
{
    var myKey = "keyE";

    functionE[myKey] = myKey + " +++ " + Date();
    return functionE[myKey];
}

But not this

alert(functionP());     // returns key and date
alert(functionP.keyP);  // RETURNS UNDEFINED

function functionP()
{
    var myKey = "keyP";

    functionP.myKey = myKey + " +++ " + Date();
    return functionP.myKey;
}

While I can do this

alert(functionT());     // returns key and date
alert(functionT.keyT);  // returns key and date

function functionT()
{
    functionT.keyT = "keyT" + " +++ " + Date();
    return functionT.keyT;
}
Machavity
  • 29,816
  • 26
  • 86
  • 96
wubbewubbewubbe
  • 701
  • 1
  • 8
  • 20

1 Answers1

4

Because functionP.myKey is equivalent to functionP['myKey'], not functionP[myKey].

functionE is the correct way of doing what you are trying to do.

You could, however, do something like this:

function functionX() {
    var key = 'keyP';
    var value = 'foo';

    this.__defineGetter__(key, function() {
        return value;
    });

    this.__defineSetter__(key, function(val) {
        value = val;
    });
}

And now it works:

> var o = new functionX()
> o.keyP
"foo"

__defineGetter__ and __defineSetter__ aren't standard JavaScript, so I wouldn't use them. Use functionE.

Blender
  • 275,078
  • 51
  • 420
  • 480