views:

95

answers:

2

Suppose you use the following structure:

var Args = new Object();
Args.Age = '10';
Args.Weight = '10';

Args.GetAge = function() {
    return 'I am ' + Age + ' years old';
}

Args.GetWeight = function() {
    return 'I weigh ' + Weight + ' pounds';
}

That works great. But is it possible to use a generic so you don't have to create a function for each variable? For example, something like the following:

Args.GetValue = function(i) {
    return this.i;
}

That doesn't seem to work but I don't even know if this is possible. Anyone know the answer to this riddle?

+4  A: 

You can access properties via [] notation:

alert(Args["Age"]);

And, as stated below, you can also just read the value via .Age or .Weight:

alert(Args.Age);

That seemed kind of obvious, so I thought you were looking for something else.

BTW, you can simplify your object creation to:

var args = { Age : '10', Weight : '10' };
Robert C. Barth
I am using an object to hold my script startup arguments and need to massage them into proper format. I have an function that retrieves the argument but I wanted to nest the function into the object instead.
Dscoduc
That did the trick! Thanks...
Dscoduc
Would it be better to declare a function for Args instead of an object? This way I could simply use the syntax var myArgs = new Args(). Of course the getValue function would change to this.getValue = function(name) { return this[name]; }
Dscoduc
That's how Microsoft AJAX works; there are functions for each setter and getter. They are prepended with _set and _get. In the prototype a class-level variable is declared, and the getter and setter return and set that variable.
Robert C. Barth
+1  A: 
var Args = {};
Args.Age = '10';
Args.Weight = '10';

alert(Args.Age);
alert(Args.Weight);

They are accessible both for read/write, you dont need setters/getters.

Luca Matteis