this keyword in Functions Javascript
this keyword in Functions Javascript
-
In a traditional function
this.a = 5; function getParam() { console.log(this.a); // this will target the parent object, which is the window object } getParam(); // 5 -
In an arrow function
this.a = 5; const getParam = () => { console.log(this.a); // this will target the parent object, which is the window object } getParam(); // 5 -
Complex Example for better understanding: #doubt
const obj = {
a: 10,
b: 20,
getTraditionalFunction: function () {
console.log("Traditional Function 'this.a':", this.a); // Refers to 'obj'
function innerFunction() {
console.log("Inner Traditional Function 'this.a':", this.a); // Refers to global object (window in browsers)
}
innerFunction(); // In strict mode, this would be undefined.
},
getArrowFunction: function () {
console.log("Arrow Function 'this.a':", this.a); // Refers to 'obj'
const innerArrow = () => {
console.log("Inner Arrow Function 'this.a':", this.a); // Refers to 'obj'
};
innerArrow();
}
};
obj.getTraditionalFunction();
// Output:
// Traditional Function 'this.a': 10
// Inner Traditional Function 'this.a': undefined (or `window.a` if not in strict mode)
obj.getArrowFunction();
// Output:
// Arrow Function 'this.a': 10
// Inner Arrow Function 'this.a': 10