让声明变量= functionName()混淆

时间:2018-04-22 10:00:33

标签: javascript

我正在阅读打字稿手册的功能;关于let声明,我很困惑:

let deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
cards: Array(52),
createCardPicker: function() {
    // NOTE: the line below is now an arrow function, allowing us to capture 'this' right here
    return () => {
        let pickedCard = Math.floor(Math.random() * 52);
        let pickedSuit = Math.floor(pickedCard / 13);

        return {suit: this.suits[pickedSuit], card: pickedCard % 13};
    }
}
}

let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();

alert("card: " + pickedCard.card + " of " + pickedCard.suit +" "+ typeof(pickedCard) 
+" "+ typeof(cardPicker));

以下两个命令看起来完全相同,但是当我打印出来时,cardPicker是一个“功能”,而pickCard是“对象”。

let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();

如果我将第一个命令更改为:

let cardPicker = deck.createCardPicker;

cardPicker和pickedCard都是“功能”

任何人都会提供更多相关细节。谢谢!

1 个答案:

答案 0 :(得分:5)

deck.createCardPicker()在调用createCardPicker()后返回该函数,并在该函数下返回该对象。

如果你只调用deck.createCardPicker,它会返回function变量但不执行实际功能。

let cardPicker = deck.createCardPicker; //返回函数变量

现在如果你打电话

let pickedCard = cardPicker(); //执行函数并返回createCardPicker()中提到的结果的函数