我有一个需要player.js
的nodeJS应用。在player.js
我定义Player
并添加方法Player.updatePacket
,但当我在main.js
中需要它并创建一个播放器实例时,player.updatePacket
未定义。
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对象中,但我仍然遇到同样的错误。任何帮助或解释都表示赞赏。
答案 0 :(得分:3)
试试这个
Player.js
var PlayerList = module.exports.PLAYER_LIST = {};
var Player = module.exports.Player = function(id) {
this.id = id;
this.x = 0;
this.y = 0
PlayerList[id] = this;
};
Player.prototype.updatePacket = function() {
return {
id: this.id,
x: this.x,
y: this.y
}
};
Main.js
var Player = require('./player.js').Player;
var PLAYER_LIST = require('./player.js').PLAYER_LIST;
io.sockets.on('connection', function(socket){
var player = new Player(socket.id)
});
setInterval(function() {
var dataArr = [];
for(var i in PLAYER_LIST) {
var player = PLAYER_LIST[i];
console.log(player);
dataArr.push(player.updatePacket()); //note that it is push not += when adding items to an array
}
broadcast("update", dataArr);
}, 1000/25);
这种解释可能过于简单化,但在JS,'类'是函数,为了将方法添加到类中,我们必须将它们添加到原型中。当我们使用' new'在该类中,它继承了其原型链中存在的所有方法。
这个链接可能被证明是一个更好的解释 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
答案 1 :(得分:2)
模块的导出是一个具有.Player
属性的对象:
var Player = exports.Player = {};
// ^^^^^^^^^^^^^^^^
因此,您需要在需要Player
对象时访问该属性:
/* main.js */
var Player = require('./player.js').Player;
// ^^^^^^^
(首选)替代方案是使Player
导出对象本身(“别名”):
/* player.js */
var Player = exports; // or = module.exports;
如果您想使用除默认对象之外的其他内容,则无法使用exports
,但必须assign to module.exports
。