我有一个可能非常简单的问题,但我无法弄清楚。我将发布一些由于某种原因不起作用的代码片段:
//authentication_handler.js
var new_user = server.authenticated_users.add_user(new User(world));
//user.js
function User(world) {
personBody = createPlayerBody(100, 100, 8, 8, false, true, world);
exports.TheBody = personBody;
}
//player_data_handler.js
module.exports = function(server, client) {
var theUser = server.authenticated_users.find_user(client.uuid);
if (theUser != null) {
var playerData = JSON.stringify({
x: theUser.TheBody.position.x, //this line throws the error below
y: theUser.TheBody.position.y
});
server.authenticated_users.each_other(theUser, function(user) {
server.send_id_message(user.client, 5, playerData);
});
}
};
我得到的错误是这样的:
Cannot read property 'position' of undefined
我对 JavaScript 还很陌生,我不知道为什么“personBody”变量没有一直传递到“player_data_handler.js”。我尝试了更多方法,但没有一个有效。非常感谢任何帮助!!
最佳答案
exports
用于导出模块的部分内容。如果您想向对象添加某些内容,请使用 this
:
尝试使用 this.TheBody = personBody; 而不是
exports.TheBody = personBody;
关于JavaScript 如何从作为参数传递的对象访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681361/