I'm new to javascript and I am confused over context and lexical environments.
Case 1:
Here I am in the global scope:
function fun() {
console.log("It works!");
}
fun(); //prints It works!
this.fun(); //also prints It works!
Am I correct to assume that the this context is implied when I write fun(); without the this keyword? Basically, here this === global/window. My question is when I type fun(), is the this implied just like I would type this.fun();? Or is it the case that when I type fun(); without the this keyword, JavaScript looks into the lexical environment at the global scope level i.e. it looks if there is a fun function declared in it's current scope that is global?
Case 2:
let cat = {
purr: function() {
console.log("meow");
},
purrMore: function() {
for (let i = 0; i < 10; i++) {
purr();
}
}
};
cat.purr();
cat.purrMore();
Why is that when I call purr in purrMore without the this., I get a reference error? If fun function in Case 1 works without the this., shouldn't it also work here without the this.?
My confusion is as follows: if in Case 1, fun function invocation without the this. keyword works because the this. is implied, then purr function invocation without the this. should also work. But if the fun function invocation without the this. keyword uses lexical environment, then it makes more sense that Case 2 doesn't work. But then, why does this code work:
function purr() {
console.log("MEOW")
}
let cat = {
purr: function() {
console.log("meow");
},
purrMore: function() {
for (let i = 0; i < 10; i++) {
purr();
}
}
};
cat.purr();
cat.purrMore(); //prints MEOW ten times
Why isn't the purr function inside cat object present in the lexical environment of purrMore?
Lastly, what topics or resources should I refer so I can remove these gaps in my knowledge?