开发者

How can you use a function that is defined below its usage?

开发者 https://www.devze.com 2023-04-10 15:08 出处:网络
I always thought that function a(){} is id开发者_Go百科entical to a = function(){}; However, these two snippets behave differently:

I always thought that function a(){} is id开发者_Go百科entical to a = function(){};

However, these two snippets behave differently:

a();
function a() {
  alert("Booya");
}

Prints Booya.

a();
a = function() {
  alert("Booya");
}

Fails with an exception, which makes sense, since a is really not defined when called.

So - what kind of 'magic' lets the first snippet work, even though a() is defined below its point of usage?


This is the difference between function declaration and function expression. This difference described well for example here.


In JavaScript all the declarations are hoisted. Means the variable can be used before it has been declared and function can be used before its declared. It’s JavaScript’s default behaviour to move all the declarations at top of the current script.

But this feature may lead to bugs in application so we use strict mode directive to avoid bugs. Strict mode does not allow to use variables without declaration.

more info at here


See this article for an explanation: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter.


No magic, proper coding is required. AFAIK

  • document is loaded and parsed, functions are 'loaded'. The the script is being executed. So far no problem _a() _ is found.
  • no function is 'maped'. The script si executed line by line. It tries to call a() and THEN assign function to a global variable a


Functions are defined global. But if you assign a function to a variable, as you do in the second case, the scope rules for variables come into effect: You can not call the function before its variable was defined.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号