Reputation: 505
My switchTurns
functions is not working when I write it as a function like this:
function switchTurns (player){
if (player == 'X'){
player = 'O';
} else {
player = 'X';
}
}
However, when I just write what is inside the declaration, it works:
if (player == 'X'){
player = 'O';
} else {
player = 'X';
}
This is where I use that: (It works when I use the commented part)
var turn = 'X';
$('.xo-btns').click(function(){
if (against != 'PC'){
show(this, turn, board);
// someoneWon(board);
switchTurns (turn);
// if (turn == 'X'){
// turn = 'O';
// } else {
// turn = 'X';
// }
}
});
How can I make the function work?
Upvotes: 1
Views: 170
Reputation: 1643
You need to setting values to turn instead player inside the switchTurns function
Jquery
var turn = 'X';
var against = "Mobile";
$('.xo-btns').click(function(){
if (against != 'PC'){
// show(this, turn, board);
// someoneWon(board);
switchTurns (turn);
console.log(turn);
}
});
function switchTurns (player){
if (player == 'X'){
turn = 'O';
} else {
turn = 'X';
}
}
Here is the working sample:https://jsfiddle.net/bu3gnpqc/
Upvotes: 1
Reputation: 354
You are changing a variable that's local to the function you've called, player. So when you call it in the function, it changes player but as soon as you've left the function the value is discarded. When you call it in the outer method, you're actually changing the variable turn.
Upvotes: 2