This course has been updated! We now recommend you take the Deep JavaScript Foundations, v3 course.
Transcript from the "Dynamic Scope" Lesson
[00:00:00]
>> [MUSIC]
[00:00:04]
>> Kyle Simpson: Remember when I discussed dynamic scope earlier? I was talking about this comparison to lexical scope, and lexical scope is an author time thing. Why don't I give you a depiction, a quick sort of theoretical depiction of what Dynamic scope would be, just so you have this contrast in your mind.
[00:00:20] Again, this is theoretical. This doesn't exist in JavaScript. But, if we had dynamic scoping inside of the function foo here on line two. On line three, when we reference a variable bar, we can clearly say lexically the bar does not exist. But, if dynamic scoping were the model that JavaScript used, it will not look for where the code was written, but it instead would look at the call stack.
[00:00:40] It would say, does function foo have a bar? If not, where was function foo called from? So it'd walk one step up the call stack and it would say, well I was called from baz. So it would look at the scope of baz to see if there was a variable.
[00:00:54] And that should look bizarre to you. It should feel awkward and unnatural, like something really strange is going on. That's because it's a totally different model for scoping than what we've all learned. We've all learned lexical. Now, if you had never learned lexical scoping and you had only ever written dynamically scoped languages, this wouldn't feel so weird and unnatural.
[00:01:15] It's not that one is right and the other one's wrong. There's a reason why lexical scoping is like 99.9% of all languages cuz it's probably superior in some ways, but the perfectly valid models are just different. And the key distinction, the key comparison that I want you to take away from this is the decision for how scoping works in dynamic scoping is a runtime decision.
[00:01:38] As opposed to in lexical sculpting it's an author time decision. So keep that distinction. The author time versus run time distinction. And that will be important when we talk about the this keyword after lunch.