Home > front end >  In js function after closure for global access to a local variable.
In js function after closure for global access to a local variable.

Time:01-16

Example: form the func function to form the closure, the func morally variables will not be regarded as garbage collection, so will exist in memory for a long time, but if I visit again in the global num why this num or undefined?
 
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 undefined

CodePudding 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 undefined

CodePudding 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 stack
So,
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

  • Related