开发者

Why are anonymous functions treated differently from named functions here? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Javascript: var functionName = function() {} vs function functionName() {}

What is the difference between a function expression vs declaration in Javascript?

Today I stumbled upon the following phenomenon:

foo();
bar();

function foo()
{
    console.log("inside foo");
}

var b开发者_开发百科ar = function()
{
    console.log("inside bar");
}

FireBug complains with the following error message:

bar is not a function

Several tutorials claim that function f() and var f = function() are basically the same thing. Evidently, they are not, but what exactly is going on here?


Function declarations are available anywhere in the scope they're defined in, even before their physical definitions.

var bar = function() { ... }; is a normal variable that happens to hold a function. Like all other variables, it can only be used after its assigned.
(You cannot observe the future value of a variable)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜