If I run the following:

var fn = function(){}

(function(){
    fn();
}());

It throws an "TypeError: undefined is not a function" in Chrome, and "TypeError: fn is not a function" in Firebug.

Shouldn't fn be available in this scope chain, without having to do window.fn?

The bizarre part is that if I run:

var fn = function(){}
console.log(fn);

(function(){
fn();
}());

Then it behaves as expected: fn is logged as a function, and no error is thrown in either Chrome or Firefox.

This is making me feel silly, like I shouldn't ever claim to understand JS.

有帮助吗?

解决方案

You forgot to add semicolon:

var fn = function(){};

(function(){
    fn();
}());

其他提示

Damn, it was ASI.

var fn = function(){};

(function(){
fn();
}());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top