简体   繁体   English

为什么这不起作用? 在循环中调用属于对象的函数

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

In my code jsc.tools is an object containing objects.在我的代码中,jsc.tools 是一个包含对象的 object。 Each sub-object contains a init() and run() method.每个子对象都包含一个 init() 和 run() 方法。

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".这给了我错误“tool.init 不是函数”。

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. javascript 中的 for in x 运算符为您提供 object 的属性名称。 Try:尝试:

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

you need to use你需要使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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