I'm reading typescript handbook's function; I'm quite confusing about let declaration:
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));
The two following commands look quite the same but when I printed out cardPicker is a "function" and pickedCard is "object".
let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();
If I changed the first command to:
let cardPicker = deck.createCardPicker;
both of cardPicker and pickedCard will both are "function"
Anybody give more details about this. Thanks!
let cardPicker = deck.createCardPicker();you are calling the createCardpicker function, therefore the cardPicker variable is now the result of it - which happens to be the arrow function you are returning. However when you dolet cardPicker = deck.createCardPicker;you are just creating an alias for the method. This way calling cardPicker will return the arrow function, thus pickerCard will be the arrow function, rather than the object you aim to return.