有什么方法可以将JavaScript类的方法作为常规函数调用?

我正在用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?

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
评论
  • 深蓝Xx
    深蓝Xx 回复

    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.