Why can I access normal functions before the declaration, but not anonymous functions?

Asked

Viewed 87 times

5

In Javascript, you can use/use a function before its declaration.

MyFunc();
function MyFunc() {
  return console.log('blah!');
}

However, when it comes to anonymous and closures functions, it is not possible to do as the above example:

var MyFunc;

MyFunc();

MyFunc = function () {
  return console.log('Nada de Blah!');
};

Even though I know it works that way, I never knew why.

Why does this happen?

  • Also dup: http://answall.com/q/63912/129

1 answer

3


In accordance with answered about PHP the compilation is done in two steps. Unlike the normal function that is a statement, the anonymous function is part of the algorithm and is not analyzed in the first step, so it cannot be considered in the first step during the analysis of the statements. In the second step is already late, only the symbols generated in the first step will be considered, or what can be interpreted up to that point of the code in the second step.

But there’s a complication. Because it is a dynamic language and the value of the variable can even no longer be a function, there is no way to guarantee that it will have the function there, the verification can only be done at the time of its execution. It’s a similar problem to include reported in PHP question.

If the language were typed MyVar would have to have the job signature, then the question code would work, no matter where the "variable" is declared. Note that I am speaking even the statement, nor need be the definition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.