This in javascript
2 min readNov 21, 2021
- This in javascript for normal function refers to object by which it is called
- This in javascript for arrow function refers to object where it is defined
Ex.1
var name = 'Neeraj Dhakar';
function displayNameByNormal() {
console.log('display name using normal function: ', this.name);
}const displayNameByArrow = () => {
console.log('display name using arrow function: ', this.name);
}const obj = {
name: 'Arvind Dhakar',
displayNameByNormal: displayNameByNormal,
displayNameByArrow: displayNameByArrow
}obj.displayNameByNormal();
obj.displayNameByArrow();Output:
display name using normal function: Arvind Dhakar
// since displayNameByNormal is a normal function so this keyword here refers to object by which it is called (in this case obj)display name using arrow function: Neeraj Dhakar
// since displayNameByArrow is a arrow function so this keyword here
// refers to object where it is defined (in this case global window // object)
Ex.2
var name = 'Neeraj Dhakar';const obj = {
name: 'Arvind Dhakar',
sayHi: function () {
console.log(' just say Hi to ', this.name); function insideNormal() {
console.log('say Hi inside normal function to ', this.name)
} const insideArrow = () => {
console.log('say Hi inside arrow function to ', this.name)
}
insideNormal();
insideArrow(); }
}obj.sayHi()Output:
just say Hi to Arvind Dhakar
// since sayHi is a normal function so this keyword here refers to object by which it is called(in this case obj)say Hi inside normal function to Neeraj Dhakar
// since insideNormal is a normal function so this keyword here
// refers to object by which it is called (in this case global // window object)say Hi inside arrow function to Arvind Dhakar
// since insideArrow is a arrow function so this keyword here
// refers to object where it is defined ( in this case obj)