Search code examples
javascriptvariablesreferenceerror

variable definition in javascript


I have no idea how to describe my question .

(function(fn){
    var able=123;
    function tmp(){
        fn()
    };
    tmp();
})(function(){alert(able)});

This snippet throws a Reference Error :able is not defined' .

Would you please explain how javascript get variables to me ?


Solution

  • Functions create lexical closures at the time of their creation. This means that when your alert function is created, the able variable does not exist. Wrapping the execution of fn in a lexical closure that does know about able at a later moment does not affect the already created lexical closure of fn.

    If you come up with a question that better explains what you are trying to do, we can propose how to properly use closures to express that idea.