我有一個nodeJS應用程序需要player.js
。在player.js
中,我定義了Player
並添加了方法Player.updatePacket
,但是當我需要它在main.js
中並創建播放器實例時,player.updatePacket
未定義。功能未定義後module.export從另一個文件
player.js:
module.exports.PLAYER_LIST = {};
var Player = exports.Player = {}
//constructor
Player.create = function(id) {
var tmp = {
id: id,
x: 0,
y: 0
};
PLAYER_LIST[id] = tmp;
return tmp;
}
Player.updatePacket = function() {
return {
id: this.id,
x: this.x,
y: this.y
}
}
main.js:
var Player = require('./player.js')
//get called by socket.io when a client connects
//didn't include socket.io setup in example for brevity, but this function
//is called as expected.
io.sockets.on('connection', function(socket){
var player = new Player(socket.id)
});
setInterval(function() {
var dataArr = [];
for(var i in Player.PLAYER_LIST) {
var player = Player.PLAYER_LIST[i];
console.log(player); //this logs: [Function]
dataArr += player.updatePacket(); //throws TypeError: not a function
}
broadcast("update", dataArr);
}, 1000/25);
我試圖移動出口語句的player.js
底部,並把updatePacket: function() {/*function contents*/}
在TMP對象,我仍然得到同樣的錯誤。任何幫助或解釋讚賞。
也有一個錯誤,你不能+ =上的對象。也就是說,你的dataArr是一個對象而不是一個數組。另外,PLAYER_LIST在哪裏? – derp
更新OP顯示PLAYER_LIST並將dataArr更改爲實際數組 –