I have created a deck of cards that contains an array of 52 card objects. Each card inherits properties and methods defined in cardObject() function. However, I am confused with how to create new deck and access its properties and methods.
// Defining properties and methods for every single card object created by PackOfCards function
function cardObject(cardNum, cardSuit) {
this.cardNum = cardNum;
this.cardSuit = cardSuit;
}
cardObject.prototype.getCardValue = function() {
if (this.cardNum === "jack" || this.cardNum === "queen" || this.cardNum === "king") {
return 10;
} else if (this.cardNum === "ace") {
return 11;
} else {
return this.cardNum;
}
}
cardObject.prototype.getCardSuit = function() {
return this.cardSuit;
}
// Creating a deck of shuffled card where every card inherits properties and methods defined in cardObject function
function PackOfCards() {
var unshuffledDeck = [],
shuffledDeck = [];
var listCardNum = ["ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "jack", "queen", "king"];
var listCardSuits = ["clubs", "diamonds", "hearts", "spades"];
for (var i = 0; i < listCardNum.length; i++) {
for (var j = 0; j < listCardSuits.length; j++) {
unshuffledDeck.push(new cardObject(listCardNum[i], listCardSuits[j])); //generating 52 new card objects
}
}
var lengthCounter = unshuffledDeck.length;
while (lengthCounter > 0) { // shuffling the 52 unshuffled cards randomly
var tempPosition = Math.floor(Math.random() * lengthCounter);
shuffledDeck.push(unshuffledDeck.splice(tempPosition, 1));
lengthCounter--
}
return shuffledDeck;
}
var newDeckObj = new PackOfCards; // I've considered PackOfCards as constructer function here
var newDeckInstance = PackOfCards(); // I've created a variable that stores a new instance of PackOfCards() function that returns an array
console.log(newDeckObj[5].getCardValue);
console.log(newDeckObj[5].getCardValue);
Here I am unable to find the real true core difference between newDeckObj and newDeckInstance.
Both contain an array of 52 objects BUT I get undefined trying to access its properties. I suppose both variables are some copy of PackOfCards() function but take different approach (one considers it a constructer which other just a function that returns an array) which I am unable to comprehend fully.