Можно ли как-нибудь вызвать метод класса JavaScript как обычную функцию? - PullRequest
0 голосов
/ 24 апреля 2020

Я пишу программу для покерных рук на 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

1 Ответ

0 голосов
/ 24 апреля 2020

В JavaScript метод класса является свойством прототипа класса, например PokerHand.prototype.getFirstCard. Так и должно быть:

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);

Вы также не помещаете ключевое слово function в начале определения метода в JS.

...