簡體   English   中英

有什么方法可以像常規 function 一樣調用 JavaScript class 的方法嗎?

[英]Is there any way I can invoke the method of a JavaScript class as a regular function?

我正在 JavaScript 中編寫一個撲克手牌計分程序,我正在嘗試重構我的代碼中有很多重復行的部分。 在 JavaScript 中,是否可以像調用常規函數那樣調用 class 方法,而不是使用標准方法語法?

這是 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中,class方法是class原型的屬性,例如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 方法定義的開頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM