I can't get to switch the player turn.

So I'm doing a tic-tac-toe game with JavaScript. I'm going with the console game first then I'll add the UI. Also, the objective is to have as little global code as possible that's why everything is inside of factories. The thing is that my gameController factory (where I control the game duh) is giving me a problem. I can't get to switch the player turn. The gameBoard is being logged correctly and it works, the problem is that every move is "made" by X player, when after each turn it should be switching. Thanks in advance πŸ™‚ Here's is the Codepen: https://codepen.io/norwyx/pen/gOJOVde?editors=0010 Here's the image so you can see what I'm logging:
No description
No description
6 Replies
Chooβ™šπ•‚π•šπ•Ÿπ•˜
You tried to use an arrow function as a constructor function. That cannot work. Rewrite Player() like this:
function Player(sign) {
this.sign = sign;
function getSign(){
return this.sign;
}
return { getSign }
}
function Player(sign) {
this.sign = sign;
function getSign(){
return this.sign;
}
return { getSign }
}
When invoking this function use "new":
const playerO = new Player("O");
const playerX = new Player("X");
const playerO = new Player("O");
const playerX = new Player("X");
The problem is the arrow function has no "this" binding of its own, so it inherits the this binding of the outer scope. It refers to the global object. The result is there is only one this.sign for both instances, because they both refer to the global object's sign property, which is defined the first time and overridden the second time. The result is that creating playerX also changes the value of sign for playerO.
Norwyx
NorwyxOPβ€’8mo ago
Oh gotcha. I tried inverting them, that is creating PlayerO before PlayerX and it worked the exact opposite way. Everything was O. Now, if it works don't touch it (your code works), but like is there any way I could use a similar syntax as in a factory without this happening? I'm asking because I truly didn't know about the "this" binding of arrow functions. Hope I don't bother you, just trying to learn more.
Chooβ™šπ•‚π•šπ•Ÿπ•˜
Just don't use arrow functions for constructor functions. Also don't use arrow functions whenever you need "this" to refer to the current object. Arrow functions take the "this" from the outer scope's "this".
Norwyx
NorwyxOPβ€’8mo ago
The project has to be done using IIEF's but Imma listen to ya. Thanks bro
Chooβ™šπ•‚π•šπ•Ÿπ•˜
I assume you meant IIFE and not IIEF. I have only ever seen them done with regular functions. I'm not even sure if it's possible to do with an arrow function, so that should make no difference in regard to my other advice.
Norwyx
NorwyxOPβ€’8mo ago
Yes I meant IIFE, mb Thanks tho
Want results from more Discord servers?
Add your server