The scope of the anonymous function passed as an argument to the function

Given the following code, what should I expect in a warning?

var a = 100;
function afunc(infunc){
  a = 10;
  infunc.call();
}

afunc(function(){alert(a)});

My initial thought was that my browser should warn 100, since the variable a = 100 would be in the scope of the anonymous function passed as an argument to afunc. But this suggests that an anonymous function is actually defined in a global context. Apparently, this is not the case when the browser warns 10. So, why is a = 10 in front of a = 100 in the visibility chain?

Thank!

+5
source share
3 answers

Because you set the value to 10 before you call an anonymous function. a is actually global, but you set it to 10.

+6
source

, a = 10 a = 100 ?

. 1 a , 100 10, .

, a , var:

var a = 100
function afunc(infunc){
  var a = 10;
  infunc.call();
}

afunc(function(){alert(a)})​
+6

:

var a = 100;

function afunc(infunc){
  a = 10;
  var f = function (){
    console.log(a);
  };
  f.call();
  infunc.call();
}

afunc(function (){ console.log(a); });

10 a afunc, , a. , 10 a, .

infunc , , afunc, , . a , a infunc.

, :

function bfunc(){
  var b = 'hello';
  return function (){ console.log(b); };
}

afunc(bfunc());

Here, the anonymous function returned bfuncis actually called from the region afunc, but it is still able to register the correct value b, since it was assigned in the original region. If you had to change afuncto assign a different value b, it would still write "hello", because the bone defined in afuncis a different variable than the bone defined in bfunc.

+1
source

All Articles