Javascript deep dive(2:Scopes)
Scope
Javascript organizes scopes with functions and blocks.All scopes are determined at compile time and used in the runtime.
excution:
Compile time: We declare variables teacher,otherclass(function) inside of global scope.We don’t declare teacher,topic variables again because it doesn’t have var/let/const.
Runtime: Now our global scope have:teacher variable,otherClass variable(function type),we assign “Kyle” into variable teacher,on line9,we excute the otherClass function,so inside of that function,that function scope don’t have any variables called teacher and topic,So we find it on the upper level.in global scope found teacher variable,and assign it with “Suzy”.Global scope don’t have any variable called “topic”,so we create one inside of global scope,and assign “React” to it.On line 11 and 12,we need to get these variable values.
Nested Scope:
global scope don’t have anotherTeacher variable.
Hoisting:
Javascript actually doesn’t have hoisting.It’s just two paths(compile time and runtime(excution time).
Some examples:
compile time:global scope have teacher variable(function type),other teacher variable.
run time:line1:run teacher variable,it’s a function.(return Kyle)
line2:run otherTeacher variable,it’s undefined.TypeError.
let doesn’t hoist?False!It’s unaccurate.
It just “hoist” in a diffrent way.
- var “hoist” in a function scope,let hoist in a block scope.
- var:When the compile time starts,create the variable and at the same
time,initialize the variable into undefined.
let/const:When let “hoisting” to it’s scope,it says create a location for the variable,but don’t initialize it.It’s different from undefined.
Closure:
What is an closure?
example:
setTimeout is an asynchronous API.so first we excute the loop,when the loop is over,we run setTimeout’s functions.When the loop is over,i is 4.
Since var does not have block scope,there is only one “i”variable ..so we console.log(4) 3 times.
here,we use “let” keyword.so every “j” catches one diffrent “i”.And setTimeout function’s callback function’s “j” is pointing to different values.
Make this more less code =>
every i has a different function scope,so the callback function inside of setTimeout points to different “i”.
Modules:
Namespace is not an module.
module core:encasplation!!!!(封装)! Hiding things/data inside!
module pattern:
- IIFE pattern(closure):
It does not expose teacher!
2.Module Factory:
We can call the module multiple times and pass different params.
ES6 module pattern:
import,export,default.