xxxxxxxxxx
// => why to choose arrow function over normal function
1. short syntax, good as callback functions
([].map(() => {}) is better than [].map(function () {}))
2. when using class component, with arrow functions no need to bind this
// example:
-// this will be undefined
button.addEventListener('click', () => {console.log(this); })
// this will refer to dom button
button.addEventListener('click', function () {console.log(this); })
In this example, we have an object with a greet method that uses an arrow function inside a setTimeout call. The arrow function has access to the enclosing scope’s this value, which is the object itself. If we had used a regular function instead of an arrow function, this would have referred to the enclosing scope instead of the object.
xxxxxxxxxx
const obj = {
name: 'John',
age: 30,
greet() {
setTimeout(() => {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}, 1000);
}
};
obj.greet(); // Hello, my name is John and I'm 30 years old.
xxxxxxxxxx
var name = "Suprabha"
let newObject = {
name : "supi",
arrowFunc: () => {
console.log(this.name);
},
regularFunc() {
console.log(this.name);
}
}
newObject.arrowFunc(); // undefined
newObject.regularFunc(); // supi