1

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!

2
  • When you do 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 do let 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. Commented Apr 22, 2018 at 10:13
  • Question has nothing to do with typescript Commented Apr 22, 2018 at 22:12

1 Answer 1

5

deck.createCardPicker() returns the function after calling the createCardPicker() and under that function you are returning the object.

If you only call the deck.createCardPicker it returns the function variable but not execute the actual function.

like

let cardPicker = deck.createCardPicker; // returns the function variable

now if you call

let pickedCard = cardPicker(); // execute the function and return the function as a result mentioned in createCardPicker()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.