This and Arrow function in JavaScript
2 min readJan 21, 2024
To understand this keyword in JavaScript, its important to understand arrow function and regular function.
Always remember below two lines for arrow function and regular function
💡 Regular function : this refers to the object that is currently calling the function.
💡Arrow function : this refers to the lexical parent of the function.
Some of the key points to remember regarding arrow function is:
- Arrow function have lexical this scope.
- Arrow function cannot be used as a constructor function.
- Arrow functions have a concise syntax and this is not hoisted.
Lets see with example to understand:
Example 1:
const objWithNormal={
name:"Bittu",
last:"Kumar",
xyz:function(){
console.log(this.name+this.last)
}
}
objWithNormal.xyz() //Bittu Kumar
const objWithArrow={
name:"Bittu",
last:"Kumar",
xyz:()=>{
console.log("vv", this.name)
}
}
objWithArrow.xyz(); //undefined
const person1={
name:"Bittu",
sayhello:function(){
function innerNormal(){
console.log(this.name)
}
innerNormal();
}
}
person1.sayhello() //Undefined
const person2={
name:"Bittu",
sayhello:function(){
const innerNormal=()=>{
console.log(this.name)
}
innerNormal();
}
}
person2.sayhello() //Bittu
Example 2:
var person = {
age: 28,
greet1: function(){
console.log("greet 1",this);
console.log("greet 1",this.age);
function greet2(){
// console.log("greet 2",this); // global object
console.log("greet 2",this.age); // undefined
}
const greet3=()=>{
console.log("greet 3",this);
console.log("greet 3",this.age);
}
greet2();
greet3();
}
}
let person1= {age: 50}
// person.greet1.call(person1);
person.greet1();
const greet4 = ()=> {
console.log(this);
console.log(this.age);
}
greet4();
I hope this example will help you undestand more about arrow function and this keyword in JavaScript.
Thanks for reading !!