Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript's Function constructor - scope issues?

Tags:

javascript

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 the Function 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 own local 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 ?

like image 743
Royi Namir Avatar asked Oct 21 '22 12:10

Royi Namir


1 Answers

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();
like image 94
Oscar Paz Avatar answered Oct 23 '22 03:10

Oscar Paz