Reputation: 41
I'm currently trying to develop a small game in NodeJS to learn ES6. I created a "Player" object with the new syntax. The static functions work perfectly. However, calling its methods throws a TypeError
(ex : TypeError: socket.handshake.session.player.joinRoom is not a function).
I don't understand why because I did the same thing I saw on several tutorials. Since joinRoom is a setter, I tried to add 'set' before the declaration but I got the same problem. Here's my code
Player.js
class Player{
constructor(name){
this.id = Player.setID()
this.name = name
this.currentRoom = ""
this.isOwner = false
this.cards = {}
Player.list[this.id] = this
}
joinRoom(code){
this.currentRoom = code
}
makeOwner(){
this.isOwner = true
}
static setID(){
if(Player.list.length === 0){
return 1
}else{
return Player.list[Player.list.length - 1].id + 1
}
}
}
Player.list = []
module.exports = Player
app.js
// socket.handshake.session.player is initialized with "new Player(playerName)"
socket.on("creatingroom", function(maxPlayers){
console.log(socket.handshake.session.player)
// Returns {id: 1, name: 'chosenName', currentRoom: '', isOwner: false, cards: {}}
var room = new Room(maxPlayers)
socket.handshake.session.player.joinRoom(room.code)
socket.handshake.session.player.makeOwner()
})
Thanks for your help
Upvotes: 4
Views: 926
Reputation: 186
While the object you are working with seems to have all the properties of the player, it looks as if it does not inherit from the Player class. You could create a new Player from that object though :
const player = Object.assign(new Player('Name'), socket.handshake.session.player);
player.joinRoom(12);
player.makeOwner();
console.log(player);
Now as player
is a real Player instance, you can now call methods on it.
Upvotes: 2