0

I am interested in how the compiler resolves this reference, on the internals. Say we have this code :

function makeConsumer(run_priority,run_object) {
        var consumer = function(last_run_action) {
                if(!!last_run_action) {
                       // do something
                } else {
                        var next_to_load = run_priority.shift();
                        next_to_load.consume = consumer;
                        run_load_script(next_to_load,run_object);
                }
        };
        return consumer;
}

There is a reference to consumer at the top, and then, before the function has finished being defined, another reference to consumer occurs in the final else block. How is this reference to consumer valid if the original consumer has not even been assigned at the time when the code is execute? I understand that function pushes scope to the top, but is this also true for a function expression assigned to a variable?

Is it possible to create a scenario in which a function references itself via a variable it is assigned to, and that reference is not yet valid? How does javascript make the second reference to consumer refer to the function, when that reference is part of the function that has not even finished being defined?

Is this equivalent to the references used in recursion? And if so, how are they evaluated by the compiler to be valid?

Cris Stringfellow
  • 3,714
  • 26
  • 48

1 Answers1

1

Javascript variable declarations are hoisted to the top. So all of these variables "exist" before they are ever referenced anywhere. So your example is equivalent to this:

function makeConsumer(run_priority,run_object) {
        var consumer; 
        consumer= function(last_run_action) {
                var next_to_load;
                if(!!last_run_action) {
                       // do something
                } else {
                        next_to_load = run_priority.shift();
                        next_to_load.consume = consumer;
                        run_load_script(next_to_load,run_object);
                }
        };
        return consumer;
}

There's more on hoisting in this question.

So when consumer is referenced in the function definition, the variable has already been declared.

The variable will also not be evaluated till the function runs. So in this case the function will not have to know what consumer is until the function is actually run (which isn't shown in your example.)

Community
  • 1
  • 1
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71