Arrow Functions in Javascript

Arrow function is the most powerful feature in ES6, especially in typescript. Like, look into one simple statement forEach.

Normal Statement with a callback function

arrayOfItems.forEach(function(x) {

//arrow function
arrayOfItems.forEach((x) => {

In a Javascript class, we use this keyword to refer to the instance of the class.But here are some cases like

myObject.myMethod1() here this used inside myMethod1 will refer to myObject.Another example you can with this snippet.

var log = console.log;

This will generate an error because log expects this to refer to console but within that reference was lost So there are ways to fix this is by bind() method.
var log = console.log.bind(console);

Another instance where this is confusing is with respect to anonymous functions
Class getDateFromServer(){
init() {}
getDataById()(function callback(err,data) {
this.init(); // this will not work

In strict mode, it will be undefined. So arrow functions don’t set a local copy of this.

Leave a reply:

Your email address will not be published.