1

I'm trying to call a function from this:

var _coll = [new Obj('a', somefunction)];
function Obj(id, fn) {
 this.id = id;
 this.fn = fn;
}
var somefunction = (function () {
 return {
 innerFn: function (a) {
 return a
 }
 }
})();
//this works
var test = new Obj('a', somefunction);
alert(test.fn.innerFn('test'));
//this is not working
loopArray();
function loopArray()
for (var it in _coll) {
 for (var its in _coll[it]) {
 var response = _coll[it].fn.innerFn('hey');
 alert(response);
 }
}
}

If I change _coll to "var test=new Obj('a','somefunction');", its ok, but how do I call a function?

Esailija
140k24 gold badges280 silver badges328 bronze badges
asked Feb 19, 2012 at 19:38
0

3 Answers 3

2

Because at the point where you define _coll, the function somefunction is not yet defined.

If you move the call which defines somefunction to top of the code, it will work just fine.

answered Feb 19, 2012 at 19:49
Sign up to request clarification or add additional context in comments.

Comments

0

First off you're using a for..in loop to access an array, which you should never do, but aside from that...

Within the first loop, _coll is the array so _coll[it] would be an element of that array. That element is your Obj object. Your second for..in loop is completely unnecessary and wrong. Surely you can see that you're doing something wrong, since you define a its variable that's never used...

answered Feb 19, 2012 at 19:45

Comments

0

Additionally to what Kolink said about the loop,
you need to move the line

var _coll = [new Obj('a', somefunction)];

behind the declaration of somefunction like you did with the line

var test = new Obj('a', somefunction);

or somefunction will be undefined.

answered Feb 19, 2012 at 19:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.