A repo to contain my notes and code examples from the Advanced JavaScript course by Kyle Simpson on PluralSight.
- Nested Scope
- Hoisting
- this
- Closure
Scope: where to look for "things" - variables (lexical identifiers)
Current version - JavaScript has function scope
Every function while executing has a reference to its current execution context called this.
this ~ dynamic scope
call site - location where the function is called
default call site example: foo();
4 rules (from spec) regarding the this keyword (in order of precedence):
- new keyword rule - when using the new keyword,
- explicit binding rule - when using .call or .apply at the call site, 1st param is this (arg)
- implicit binding rule - base object/context object at the call site becomes the this keyword
- default binding rule - if you are in strict mode, this is undefined, otherwise this is global
hard binding - make it such that you can predict what "this" is
whenever the "new" keyword is used:
- brand new empty object created out of thin air
- object gets linked to another object*
- bound as the this keyword
- if the function doesn't return anything, implicitly return this
How To Use The 4 Rules (find the call site and ask these 4 Rules):
- Was the function called with "new"?
- Was the function called with "call" or "apply" specifying an explicit this?
- Was the function called via a containing/owning object(context)?
- DEFAULT: global object (except strict mode)
from lambda calculus
(def) Closure is when a function "remembers" its lexical scope even when the function is executed outside that lexical scope.
created when an inner function is transported outside of a given function (returned)
Common OO Patterns Prototype Inheritance vs. Behavior Delegation
prototype
Every single "object" is built by a constructor function
Each time a constructor is called, a new object is created; not an "instance"
A constructor makes an object linked to (based on) its own prototype
A constructor is a statement with the "new"
[[Prototype]] is a prototype linkage
The affect is that prototype chain keeps delegating up the chain until there is resolution
3 ways to find out where an object's [[Prototype]] points to:
- .proto (dunder proto)
- Object.getPrototypeOf
- .constructor.prototype (hacky)
In essence in reverse of classical OO inheritance, prototypal inheritance; behavior delegation
Behavior Delegation (design pattern)
OLOO: Objects Linked to Other Objects
- Callbacks
- Generators / Coroutines
- Promises