The function func () {
Var num=1
Return the function () {
The console. The log (num)
}
}
Var a=func ()
(a)
The console. The log (num)
CodePudding user response:
Definition of var variable in a function scope , only in the function body, can't access outside a function, this with closures it doesn't matter,CodePudding user response:
The function func () {
Var num=1
Return the function () {
The console. The log (num) a (),//call here can access to the num func
}
}
Var a=func ()
(a)
The console. The log (num)//visit here is the window. The num
CodePudding user response:
In fact is the scope of the problem, the scope of a variable num in method func, outside can't access, so it is undefinedCodePudding user response:
Isn't in memory will separate give this function to set up a large space, and then in the large space in opening up a small space to store the num, then at the time of our js code executes in the global access num he will find, in func with other memory block at the does not go deep into the inside func, then will be undefinedCodePudding user response:
Will enhance the scope of the var, it is the precondition of var method in the same stack, var can't beyond their own method and function to other method stackSo,
The function func () {
Var is num=1//this method is num in func method stack
Return the function () {
The console. The log (num)
}
}
Var a=func ()
(a)
The console. The log (num)//the num is the main method in the stack, the num cross method above stack scope upgrade
The
for(let i=0; i<4. I++) {
Var j=I;//this j, although in the for local, belongs to the main method stack at the time,
}
The console. The log (j);//so you can scope, here or in the main method stack, the scope and LZ code completely different