Can someone help me understand the object oriented approach to javascript? I am used to writing js code as follows:
function o_deal(id) {
var hand = gcard1 + ", " + gcard2;
var res = gcard1_val + gcard2_val;
document.getElementById(id).innerHTML = hand;
if (res == 21) {
alert("Blackjack!");
}
if (bucket == 0) {
bucket = " ";
}
var card3_val = Math.floor(Math.random() * deck.length);
var nhand = deck[card3_val];
bucket = bucket + " " + nhand + ", ";
bucket_val = bucket_val + gcard1_val + gcard2_val + card3_val;
if (bucket_val >= 22) {
var r = confirm("Bust! By " + nhand);
if (r == true) {
refresh();
}
else {
refresh();
}
}
document.getElementById(id).innerHTML = bucket;
}
But I’ve seen a number of posters on stack overflow that write code like this:
var Hand = function(bjcallback) {
this.cards = [];
this.onblackjack = bjcallback;
this.deck = [1,2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"];
this.values = {
"Jack": 10,
"Queen": 10,
"King": 10,
"Ace": 11
};
this.sum = function() {
var i, x, res = 0;
for (i in this.cards) {
x = this.cards[i];
if (typeof(x) != 'number') { x = this.values[x] };
res += x;
};
return res
};
this.pick = function() {
var pos = Math.floor(Math.random() * this.deck.length);
var card = this.deck[pos];
console.log(card);
return card
};
this.deal = function(n) {
n = n || 2;
Can someone please break the second method down so I can understand the difference? Any help would be appreciated.
Object orientation in javascript is not two hard. You just bundle functionality and data together.
So we have some functionality.
I’ll just look at this snippet
Let’s refactor this. We would need a few functions
Now we need to define hand.
Now we can refactor
o_dealtoOf course we still need the concepts of cards and we need to be able to make a hand.
Making a hand is easy.
var hand = Object.create(Hand)We also need a Card object which needs a
toStringmethodNow we just need a way to create a hand
Now hopefully you can see how encapsulation and binding data and functionality together is useful.