ishehroze / angular-six-test

This repository contains angular 6 excercises for me and mohin bhai
https://ishehroze.github.io/angular-six-test/
0 stars 0 forks source link

2.5 Fat Arrow Functions #26

Open ishehroze opened 1 month ago

ishehroze commented 1 month ago

See: https://codecraft.tv/courses/angular/es6-typescript/arrow/ Fat arrow functions have a concise syntax and, most importantly, doesn't change the calling context for this.

let obj = {
    name: "asim",
    sayLater: function () {
        console.log(this); // `this` points to obj
        setTimeout(() => {
            console.log(this); // `this` points to obj
            console.log(`${this.name}`); // `this` points to obj
        }, 1000);
    }
};
obj.sayLater();

If we were to replicate the same behavior without the fat arrow function, we would need to store this to a separate variable (e.g. self) in the appropriate context first and then call the variable where this changes the calling context.

let obj = {
    name: "asim",
    sayLater: function () {
        let self = this; // Assign to self
        console.log(self);
        console.log(this); // `this` points to obj
        setTimeout(function () {
            console.log(`${self.name}`); // Use self not this
        }, 1000);
    }
};
ishehroze commented 1 month ago

The lesson referred doesn't require any changes to this repository