1

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.

4
  • This is just procedural vs OO. Can you be more specific about what you dont understand? Commented Jul 27, 2011 at 22:35
  • I don't understand the OO syntax at all. I would point out more but I cannot follow the code. What are the literal differences between OO and procedural? Commented Jul 27, 2011 at 22:37
  • you would need to compare two bigger snippets Commented Jul 27, 2011 at 22:38
  • I am also trying to get a grasp of the object oriented approach. I have been to so many resources and there is so many different ways to create objects... it's very confusing. Commented Jul 27, 2011 at 22:39

4 Answers 4

2

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

function o_deal(id) {
    var hand = gcard1 + ", " + gcard2,
        res = gcard1_val + gcard2_val;

    document.getElementById(id).innerHTML = hand;

    if (res == 21) {
        alert("Blackjack!");
    }
}

Let's refactor this. We would need a few functions

  • isBlackjack. for checking whether we've won.
  • toString for rendering the hand

Now we need to define hand.

var Hand = {
   "isBlackjack": function() {
     return this.cards[0].value + this.cards[1].value === 21;
   },
   "toString": function() {
     return this.cards[0].toString() + " " + this.cards[1].toString();
   }
 }

Now we can refactor o_deal to

function o_deal(id, hand) {
    document.getElementById(id).innerHTML = hand.toString();

    if (hand.isBlackjack()) {
        alert("Blackjack!");
    }
}

Of 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 toString method

var CardList = [null, "1","2","3","4","5","6","7","8","9","X","A"];

var Card = {
  "toString": function() {
    return CardList[this.value];
  }
}

Now we just need a way to create a hand

var createHand = function() {
  var hand = Object.create(Hand);
  var card1 = Object.create(Card);
  var card2 = Object.create(Card);
  card1.value = Math.floor(Math.random() * 11);
  card2.value = Math.floor(Math.random() * 11);
  hand.cards = [card1, card2];
  return hand;
}

Now hopefully you can see how encapsulation and binding data and functionality together is useful.

Sign up to request clarification or add additional context in comments.

2 Comments

I still have ways to go to fully understand OOP, but this shed some much needed light. Thank you Raynos.
@codeninja I also recommend you ignore anyone who says anything about inheritance and look at traits. Traits allow you to re-use functionality and build bigger objects out of many smaller ones
2

Douglas Crockford is your man. He has a series of articles that really delve into the finer points of JavaScript. I recommend reading all of the articles:

http://javascript.crockford.com/

This one explains JavaScript's OO syntax:

http://javascript.crockford.com/private.html

Comments

1

object oriented comes into play when the whole thing is in Class.

1 Comment

could you elaborate a little more? When what whole thing is in Class? And how does OO make life easier when it is in Class?
1

Object oriented code is for organization and reusability. So in your second example, you have a class Hand, that you can create new instances of. So every time you want to create a new hand of cards for a player, you could do:

var playerHand = new Hand(options);

and pass in parameters to the class, which would be used to differentiate one hand from the other.

this.deck, this.cards, etc. are properties of the object, and this.sum, this.pick, etc are methods. These methods (or simply functions) can act upon the public and private properties of the object.

This particular example of OO code wouldn't be a real world example (or at least I wouldn't organize it that way). The "deal" method would be part of the CardDealer class.

So you would have the following Classes/Objects (amongst others), from which you can create new instances:

Dealer, Player, Hand, Card, Game

(Mind you, this is just one approach, as you mentioned, there are many ways to go about this) The Game object could have a "type" property, in which case it would be blackjack. The Game object could then be responsible for loading the appropriate rules for blackjack. One instance of Dealer would be needed, and X amount of Player objects as well, and each would have a Hand object associated with it.

This way, each object is responsible for its own properties and actions (methods). It keeps everything organized and encapsulated.

As I'm writing this, @Raynos just posted examples of rewriting your procedural code as OO, so hopefully this might help you with the whys instead of the hows.

1 Comment

This was a much needed complement to Raynos's breakdown. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.