Javascript (六):Know 'Closure' Inside Out?
What is closure?
In JavaScript, closures are often regarded as some sort of magical unicorn that only advanced developers can really understand, but truth be told it is just a simple understanding of the scope chain. A closure, as Douglas Crockford says, is simply:
An inner function always has access to the vars and parameters of its outer function, even after the outer function has returned…
The code below is an example of a closure:
// ==>进入全局执行上下文 var dongcCard = card('dongc'); dongcCard(); function card(sname) { var gender = 'male'; return function showInfo() { console.log('[carInfo] name:%s gender:%s', sname, gender); } }
read above code , have two doubts:
- 为何card函数在定义之前,可以被调用?
- 为何card函数执行完毕后,card函数中“gender”属性仍然可以被访问?
究其原由,深入内核底层,一探究竟。
How do javascript engine work?
The JavaScript interpreter in a browser is implemented as a single thread. Actions or Events being queued in what is called the execution stack. The diagram below is an abstract view of a single threaded stack: Read More...