io.sockets.on('connection', function (socket) {
socket.on('requestGame', function (data) {
for (var game in games)
if (game.player2 === undefined) {
game.player2 = socket;
socket.emit('gameStart', { game_id: game.game_id, turn: !p1_turn }); // works
game.player2.emit('gameStart', { game_id: game.game_id, turn: !p1_turn }); // doesn't work
为什么其中一条线路有效而另一条线路没有?
这是错误
game.player2.emit('gameStart', { game_id: game.game_id, turn: !game.p1_tur
^
TypeError: Cannot call method 'emit' of undefined
答案 0 :(得分:1)
for (var a in b)
语法遍历b的键。每次循环时,a都是一个字符串,而不是你可能正在寻找的b的值。
因为它是一个字符串和一个文字,所以附加一个属性将立即对它没有任何影响。您无法在Javascript中更改字符串和数字等文字。
'hello'.foo = 'world';
console.log('hello'.foo); // undefined
var str = 'hello';
str.foo = 'world';
console.log(str.foo); // undefined
你可能想做的是
for (var key in games)
var game = games[key];
if (game.player2 === undefined) {
game.player2 = socket;
socket.emit('gameStart', { game_id: game.game_id, turn: !p1_turn }); // works
game.player2.emit('gameStart', { game_id: game.game_id, turn: !p1_turn }); // doesn't work