This code new Function('fn', 'fn()')
creates anonymous function which has param and (in this case the param is a function) executed.
Doing console.log(new Function('fn', 'fn()'))
shows the output :
function anonymous(fn)
{
fn()
}
Now , the docs states :
Note:
Functions
created with theFunction constructor
do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their ownlocal variables and global ones
, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.
Ok.
So why does this code yields 1
and not 44
?
var a = 44;
function myFunc()
{
var a = 1;
function f()
{
alert(a)
}
new Function('fn', 'fn()')(f);
}
myFunc();
Why ?
What about this line above ?
they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called
It looks like the f
is closure over the parent a
, but how come ? it suppose to be run at global , and able to access local and global only !
What am I missing ?
Because you're invoking function f
, which is a normal function that does create a closure.
The documentation refers to this:
var a = 44;
function myFunc()
{
var a = 1;
new Function('fn', 'alert(a)')(); //shows 44, not 1
}
myFunc();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With