//现在已回答 - 请参阅代码行
我抛出异常,因为据说我调用的方法没有声明。但实际上是这样,所以我不确定为什么会发生
Uncaught TypeError: Object #<Unit> has no method 'onLoopEvent'
代码是
function Unit () {
var item = new Item();
item.onLoopEvent = function( index ) {
...
}
return item; // <--- WAS missing this - as pointed out first by ars265
}
items[ items.length ] = new Unit();
// main loop that gets called periodically
function onLoop () {
for( var i=0; i < items.length ; i++ ) {
var item = items[ i ];
item.onLoopEvent( i );
}
}
我不明白为什么会发生这种情况。看起来该方法声明正确
最佳答案
事实上,您没有从 new Unit()
返回任何内容,因此您将数组索引项设置为 undefined
,这导致了您的问题。
更正
更正后,您不会返回 undefined
,因为这是函数在没有返回值的情况下返回的内容。相反,您将返回 Unit
函数的新实例。这就是我一边吃饭一边回答的结果。 ;)
关于javascript - 未捕获的类型错误 : X has no method 'Y' - but Y *is* declared,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18598010/