pav
5/20/2013 - 6:21 PM

By default in Javascript, all properties are made public. This means that at any point in the program, the properties can be accessed or cha

By default in Javascript, all properties are made public. This means that at any point in the program, the properties can be accessed or changed.

In some cases that's what we want. But in our Blackjack game, it can get us in trouble. To see how, look at the code to the right. First, we have put in a sample Card constructor (without the getters), and then we have made a function cheat (line 21). It simply checks to see if there is a property called number, then changes the numbers of the two cards to 13 and 1 to get an ace and a king. Hit run to see that cheat does indeed work, automatically giving the player blackjack!

One important lesson of object-oriented design is to make things private when we can. In this case once a card is created and dealt out, we probably don't want to change what's on the card. That way, even if another function knows the name of our properties, they won't be able to change them from the outside!

// change our card constructor to make suit and number private
function Card(s, n) {
    this.suit = s;
    this.number = n;
}

// let's say someone is initially dealt bad cards
var card1 = new Card(2, 7);
var card2 = new Card(3, 6);

// but they have figured out a way to cheat our system!
function cheat() {
    if(card1.hasOwnProperty("number")) {
        console.log("I first have a "+card1.number+" and a "+card2.number);
        card1.number = 13;
        card2.number = 1;
        console.log("haha now I have blackjack!");
    }
}

cheat();