Original Code - Version 1:
const myobj = {
a1 : 10,
b1 : 20,
c1 : 30,
myfunc1 :function() {
console.log(this)
const myfunc2 = function () {
let a2 =100
console.log(this)
}
myfunc2()
}
}
myobj.myfunc1()
Output:
{a1: 10, b1: 20, c1: 30, myfunc1: ƒ}
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
Revised Code - Version 2:
const myobj = {
a1 : 10,
b1 : 20,
c1 : 30,
myfunc1 :function() {
console.log(this)
const myfunc2 = () => {
let a2 =100
console.log(this)
}
myfunc2()
}
}
myobj.myfunc1()
Output:
Object a1: 10 b1: 20 c1: 30 myfunc1: ƒ ()[[Prototype]]: Object
Object a1: 10 b1: 20 c1: 30 myfunc1: ƒ ()[[Prototype]]: Object
I am struggling to grasp the behavior of the 'this' keyword in JavaScript.
Issue Faced: In the first version of the code, when I use the 'this' keyword inside myfunc1, it refers to myobj. However, when I create another function like myfunc2 and call it within myfunc1, it references the window object. I am puzzled by this behavior, especially since the functions are created and called within the myobj object literal.
In the second version of the code, the 'this' keyword inside myfunc1 points to myobj, as expected. Additionally, when the arrow function myfunc2 is created inside myfunc1, it correctly references the myobj object literal because arrow functions capture the scope in which they are created.
My confusion lies in why, in the first version of the code, even though the functions are within the myobj literal, the 'this' keyword still references the window object.