Dscoduc
Dscoduc

Reputation: 7754

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

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?

Upvotes: 3

Views: 303

Answers (2)

Luca Matteis
Luca Matteis

Reputation: 29267

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.

Upvotes: 1

Robert C. Barth
Robert C. Barth

Reputation: 23325

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

Upvotes: 4

Related Questions