最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can you use a function that is defined below its usage? - Stack Overflow

programmeradmin5浏览0评论

I always thought that function a(){} is identical 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?

I always thought that function a(){} is identical 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?

Share Improve this question asked Oct 5, 2011 at 10:20 ripper234ripper234 230k280 gold badges645 silver badges914 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

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./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 e into effect: You can not call the function before its variable was defined.

发布评论

评论列表(0)

  1. 暂无评论