2

How can I call each function in this object?

var obj = {
  hey1: function() {
    alert('hey');
  },
  hey2: function() {
    alert('hey2');
  },
  hey3: function() {
    alert('hey3');
  }
}

I'd like each function to run one after the other. I'm looking for something like:

for (var hey in obj) {
  hey();
}

But obviously that doesn't run (otherwise I wouldn't be asking this question).

Thanks guys!!!

1
  • If only javascript reflection.. Commented Feb 1, 2011 at 6:34

2 Answers 2

7
for (var hey in obj) {
    obj[hey]();
}

In a situation where it is not guaranteed that each property will be a function, you can weed out other properties:

for (var hey in obj) {
    if (typeof obj[hey] == "function") {
        obj[hey]();
    }
}

To further restrict it to only immediate properties of the object (and not the ones inherited from its prototype):

for (var hey in obj) {
    if (typeof obj[hey] == "function" && obj.hasOwnProperty(hey)) {
        obj[hey]();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Lopping will give you they keys, not the values. Use the key to get the value:

for (var hey in obj) {
  obj[hey]();
}

jsfiddle.net/s8tbr/

Note: Depending on from where you get the object, you might want to check that the properties are members of the object itself, not inherited from a prototype:

for (var hey in obj) {
  if (obj.hasOwnProperty(hey)) {
    obj[hey]();
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.