1

I have a javascript object with some functions inside, I wish I could call them in a loop, something like this:

funcs: {
  func1: function() {
      return true;
  },
  func2: function() {
      return false;
  }
}

for(func in funcs) {
   console.log(funcs[func]());
   console.log(funcs[func].call());
}
4
  • 7
    your wish is granted (i.e. that code works) Commented Sep 10, 2014 at 22:24
  • which one of them I'm curiour -> the .call() or the() Commented Sep 10, 2014 at 22:26
  • both work fine. I don't really know the difference though. Commented Sep 10, 2014 at 22:31
  • 1
    They both work (change to var funcs = {...}). The second version will default the context to the global object unless an object instance is passed in as the first parameter: funcs[func].call(funcs) Commented Sep 10, 2014 at 22:32

1 Answer 1

2

Both work. But the declaration of your object is not correct. It is var object = { /*something*/};

var funcs = {
  func1: function() {
      return true;
  },
  func2: function() {
      return false;
  }
};

for(func in funcs) {
   console.log(funcs[func]());
   console.log(funcs[func].call());
}

Output

true
true
false
false
Sign up to request clarification or add additional context in comments.

3 Comments

Here you can loop with for(func in obj.funcs) {}
what is obj? There is no object or variable called obj here.
I was answering to a comment that apparently has been deleted.

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.