I've been reading a little bit into execution contexts and lexical scoping. From my understanding, if a function is declared, it will have a reference to the lexical environment (LE) that defined that function. for example,
var x = 20;
function foo() {
console.log(x);
}
So the reason why foo has access to variable x is because foo's LE has a reference to the LE which created foo which is the global LE so it can search through the scope chain until it finds x.
however for the following snippet:
var stacy = {
name: 'stacy',
age: 33,
sayName: function() {
console.log(this.name);
}
}
What is the LE of the object stacy? (I believe it would be the global LE)
What is the LE of the sayName()? (if I omit the "this" keyword, why couldn't it find the variable "name" when the function couldn't find "name" in its own LE)?
I use "scope" instead of "LE" here, as the former is more common in JavaScript learning resources.
Functions have their own scope; objects do not. So while (1) the scope of
stacyis indeed the global scope, (2) the code ofsayNameruns in its own scope, for which the parent scope is the global scope.this.nameworks because non-arrow functions have an additional bindingthisadded to their scope, butnamedoesn't work because the object isn't a scope, it's just a data structure with a 'name' property.stacy.namewould work, and you could declare anamevariable with anothervarorletstatement that would work in either scope.