Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
Dscoduc Avatar asked Jan 29 '26 04:01

Dscoduc


1 Answers

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' };
like image 164
Robert C. Barth Avatar answered Jan 31 '26 19:01

Robert C. Barth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!