Shikha thakur - 2 months ago 6

TypeScript Question

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.

Answer

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.

Source (Stackoverflow)

Comments