Thursday, April 14, 2011

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
}
From stackoverflow
  • 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();
    }
    
    Pim Jager : This has caught me quite a few times too. You'd think the for(x in ..) would set x to the object/array/string/whatever, but it only sets x to the key.
  • you need to use

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

0 comments:

Post a Comment