I have been using the w3 org's JavaScript Best Practices web page's examples for coding an object literal for a game.
It is my understanding that I should use this to keep all my variables and arrays that are not associated with/inside functions. I should then use methods to access and update the values and arrays.
I wanted to make sure I was on the right track (and learning code practices) before I got too far into the code.
So, using the code listed below, I would access values as follows:
var valueSquareA = t3Game.checkSquare(a);
and
var arrSq = t3Game.getSquares();
var t3Game = (function(){
var playerImg = "images/blankSpace.gif";
var compImg = "images/blankSpace.gif";
var squares = []; // For keeping track of the board.
return{
getImgFileName: function(playerOrComp){
if(playerOrComp ==="player"){
return playerImg;
}
else {
return compImg;
}
},
setImgFileName: function(choice){
if(choice === "X"){
playerImg = "images/X.gif";
compImg = "images/O.gif";
}
else {
playerImg = "images/O.gif";
compImg = "images/X.gif";
}
},
setBoard: function(){
for(i=1; i<=9; i++){
squares[i] = "empty";
}
// alert(squares);
},
setSquare: function(nbr, playerOrComp){
squares[nbr] = playerOrComp;
// alert(squares);
},
checkSquare: function(nbr){
return squares[nbr];
},
getSquares: function(){
return squares;
}
} // end return
})();