Я пишу программу для покерных рук на JavaScript и пытаюсь реорганизовать часть своего кода, в которой много повторяющихся строк. Вместо того, чтобы использовать стандартный синтаксис метода, возможно ли в JavaScript вызывать методы класса, как если бы вы выполняли обычные функции?
Вот Python эквивалент того, что я пытаюсь сделать:
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?
Я пытался использовать call()
и apply()
, оба не работают, к сожалению.
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