scope chain, although the topics of closures can draw pictures, they are all abstract
specific to the implementation, I still have some problems
question 1: does the execution environment in closures need to be unstacked
take a look at the following function
function A(i) {
return function (n) {
console.log(n + i); //xf0 function(n){console.log(n + i);}
} }
var B = A(10); //0 B=xfo
B(20);
When time 0 An is executed, windowscontext-Acontext
An in the stack is finished, and there is a closure. The context of A does not destroy
but should Ac be out of stack? (I think it should still be out of the stack)
before executing B (20), should An enter the stack (or not)
, that is, whether the stack at this time is wc-Ac-Bc or Wc-Bc
Why do you ask the first question, because I have two guesses about the implementation of the scope, and I"m not sure
question 2:
there are two guesses: 1. Stored in variable objects in each execution environment (that is, the scope chain is an actual object),
2. There is no br chain (that is, no storage), and the required variables are automatically obtained according to the execution environment order of the execution stack. This mechanism is called scope chain (that is, the scope chain is a virtual non-existent thing) < domain > make an explanation:
var a = 1 //0
function A () {
B() //2
function B(){
a = 10
}
}
A() //1
console.log(10)
moment 0 the windows execution environment enters the stack,
time 1 br An execution environment enters the stack,
time 2 jewel B execution environment enters the stack,
at this time the bottom of the stack-- the top of the windowscontext--Acontext--Bcontext--Ccontext-- stack
if it is case 1, there is an attribute in variable object in Ccontext that records the scope chain. It doesn"t seem to be easy to implement this principle.
if case 2 scope is just a concept, there is no such practical thing as scope. When I visit a, I visit variable object in Ccontext first, and I don"t look for it in the variable object of context at the bottom of the stack step by step until I find the bottom of the stack.
ask for the guidance of the Great God