How to use nested functions in objects

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';
}

This works great. But is it possible to use a generic type, so you do not need to create a function for each variable? For example, something like the following:

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

This does not work, but I do not even know if this is possible. Does anyone know the answer to this riddle?

+3
source share
2 answers

You can access properties through the [] notation:

alert(Args["Age"]);

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

alert(Args.Age);

It seemed obvious, so I thought you were looking for something else.

BTW, you can simplify the creation of your object:

var args = { Age : '10', Weight : '10' };
+4
source
var Args = {};
Args.Age = '10';
Args.Weight = '10';

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

/, /.

+1

All Articles