Macha
Macha

Reputation: 14664

Why doesn't this work? Calling functions belonging to objects in a loop

In my code jsc.tools is an object containing objects. Each sub-object contains a init() and run() method.

I have the following code running at startup:

for(tool in jsc.tools) {
    tool.init();
}

which gives me the error "tool.init is not a function".

A sample of a tool's declaration is:

jsc.tools.sometool = {};
jsc.tools.sometool.run = function() {
    // Apply tool
}
jsc.tools.sometool.init = function() {
    // Set bits of data needed for the tool to run
}

Upvotes: 0

Views: 91

Answers (2)

bendewey
bendewey

Reputation: 40245

you need to use

for(tool in jsc.tools) {
    jsc.tools[tool].init();
}

Upvotes: 0

Staale
Staale

Reputation: 27998

The for in x operator in javascript gives you the names of the properties off an object. Try:

for(tool in jsc.tools) {
    jsc.tools[tool].init();
}

Upvotes: 5

Related Questions