0

I am learning typescript and got stuck in one of the topic "functions"

Where i gone through the sub topic Lambdas and using this

here when i did with normal function expression i m getting error

let deck = {
    suits: ["hearts", "spades", "clubs", "diamonds"],
    cards: Array(52),
    createCardPicker: function() {
        return function() {
            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);

but when i used arrow syntax (() => {}) rather than the JavaScript function expression its working fine and i am geting alert

 let deck = {
        suits: ["hearts", "spades", "clubs", "diamonds"],
        cards: Array(52),
        createCardPicker: function() {
            // Notice: the line below is now a lambda, allowing us to capture 'this' earlier
            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);

but the thing is i am unable to get what was the issue with first one

i have went through the DOCS

but unable to understand it clearly

Any explanation is appreciated.

Shikha thakur
  • 1,229
  • 10
  • 30
  • 1
    as always the difference is about **this** maybe reading the MDN documentation for arrow functions will help? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – toskv Sep 08 '16 at 11:48
  • sure i'll go through it – Shikha thakur Sep 08 '16 at 12:04

1 Answers1

3

You are using this inside the function you are returning.

Usually, the value of this depends on how a function is called.

An arrow function lexically binds the this value from the scope it is created in.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205