简体   繁体   中英

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
}

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();
}

you need to use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM