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) {
updatedItems.push(x+1);
});

//arrow function
arrayOfItems.forEach((x) => {
updatedItems.push(x+1);
});

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;
log('Hello');

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);
log('Hello');

Another instance where this is confusing is with respect to anonymous functions
Class getDateFromServer(){
init() {}
fetchData(){
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.