Reputation: 35
I am writing a poker hand scoring program in JavaScript, and I am trying to refactor a part of my code that has a lot of repeating lines. Rather than using the standard method syntax, is it possible, in JavaScript, to invoke class methods like you would regular functions?
Here is the Python equivalent of what I am trying to do:
class PokerHand:
def __init__(self, cards):
self.cards = cards
def getFirstCard(self):
return self.cards[0]
hand = PokerHand(['ace of spades', 'king of spades', 'queen of spades', 'jack of spades', '10 of spades'])
hand.getFirstCard() # standard way of invoking methods
PokerHand.getFirstCard(hand) # is there a JavaScript equivalent of this?
I tried using call()
and apply()
, both do not work, unfortunately.
class PokerHand {
constructor(cards) {
this.cards = cards;
}
function getFirstCard() {
return this.cards[0];
}
}
const hand = new PokerHand(['ace of spades', 'king of spades', 'queen of spades', 'jack of spades', '10 of spades']);
PokerHand.getFirstCard.call(hand); // doesn't work
PokerHand.getFirstCard.apply(hand); // doesn't work
new PokerHand(someListOfCards).getFirstHand.call(hand) // no error but returns the wrong result
Upvotes: 0
Views: 24
Reputation: 780871
In JavaScript, a class method is a property of the class prototype, e.g. PokerHand.prototype.getFirstCard
. So it should be:
class PokerHand {
constructor(cards) {
this.cards = cards;
}
getFirstCard() {
return this.cards[0];
}
}
const hand = new PokerHand(['ace of spades', 'king of spades', 'queen of spades', 'jack of spades', '10 of spades']);
const firstCard = PokerHand.prototype.getFirstCard.call(hand);
console.log(firstCard);
You also don't put the function
keyword at the beginning of a method definition in JS.
Upvotes: 1