有什么方法可以将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?

我尝试使用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

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

您也不会在JS中的方法定义的开头放function关键字。

相关内容

最新更新