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:
6 Replies
You tried to use an arrow function as a constructor function. That cannot work.
Rewrite Player() like this:
When invoking this function use "new":
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.
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.
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".
The project has to be done using IIEF's but Imma listen to ya. Thanks bro
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.
Yes I meant IIFE, mb
Thanks tho