1

// 现在回答 - 见代码行

我被抛出了一个异常,因为据说我正在调用的方法没有被声明。但实际上是这样,所以我不确定为什么会这样

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

我不明白为什么会这样。看起来该方法已正确声明

4

4 回答 4

0

new Unit()返回一个Unit实例,而不是一个Item实例。该items数组仅包含对Unit实例的引用。

这是你可以做的:

function Unit () {
     this.item = new Item();
     this.item.onLoopEvent = function( index ) {
         ...
     }
}

然后在循环中:

// main loop that gets called periodically
function onLoop () {
    for( var i=0; i < items.length ; i++ ) {
    var unit = items[ i ];
    unit.item.onLoopEvent( i );
    }
}
于 2013-09-03T17:24:52.123 回答
0

我猜你的意思是:

var Item = function() {}
function Unit () {
     var item = new Item();
     item.onLoopEvent = function( index ) {
         console.log(index);
     }
     return item;
}
var items = [];
items[ items.length ] = Unit();

// main loop that gets called periodically
function onLoop () {
    for( var i=0; i < items.length ; i++ ) {
    var item = items[ i ];
    item.onLoopEvent( i );
    }
}
onLoop();

你应该在 Unit 中返回一些东西。或者如果你不返回,那么你应该使用this.item = new Item(); 将某些东西附加到 Unit 功能。否则,您新创建的 Item 只会留在 Unit 的范围内。

请注意,我没有在 Unit 中使用new infront。那是因为我正在调用该函数而不是创建一个新实例。

于 2013-09-03T17:25:24.997 回答
0
function Unit() {
    this.onLoopEvent = function (index) {
        //...
    };
}

var items = [];
for (var i = 0; i < 5; ++i) items.push(new Unit());

function onLoop() {
    var i;
    for (i = 0; i < items.length; ++i) {
        items[i].onLoopEvent(i);
    }
}
于 2013-09-03T17:27:41.447 回答
0

对于您没有返回任何内容的事实,您new Unit()将数组索引项设置为undefined,这会导致您出现问题。

更正 更正后,您没有返回undefined,因为如果没有返回值,这是函数返回的内容。Unit相反,您正在返回该函数的一个新实例。这就是我同时吃饭和回答的结果。;)

于 2013-09-03T17:27:48.367 回答