first version of code :
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, …}
second version of code :
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 having trouble understanding the this keyword behaviour in javascript
my problem : In my first version of code when I call this keyword inside myfunc1 then it is referencing myobj but inside the same function when I create another function as myfunc2 and call it inside the function then it is referencing the window object why it is behaving like this even though the function is called and created inside the myobj object literal
In my second version of code when I call this keyword inside myfunc1 then it is referencing myobj and inside the same function when I create another function as myfunc2 and call it inside the function myfunc1 the it is referencing the myobj object literal as the arrow function takes the scope in which it has been created
my problem is why in first version of code even though the function is created and called inside the myobj literal it is referencing the window object