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 stacy
is indeed the global scope, (2) the code of sayName
runs in its own scope, for which the parent scope is the global scope. this.name
works because non-arrow functions have an additional binding this
added to their scope, but name
doesn't work because the object isn't a scope, it's just a data structure with a 'name' property. stacy.name
would work, and you could declare a name
variable with another var
or let
statement that would work in either scope.