run
run

Reputation: 553

javascript anonymous function

function (){
    alert('a function');
}

when i put it on the firebug javascript control. it shows function statement requires a name

(function (){
    alert('a function');
}())

when i put the above it shows ok.

function (){
    alert('a function');
}()

it also shows function statement requires a name and doesn't execute the function. why?

Upvotes: 0

Views: 86

Answers (1)

xdazz
xdazz

Reputation: 160933

function (){
    alert('a function');
}

is a function statement, so it requires a name.

(function (){
    alert('a function');
}())

The () change the statement to an expression, so it's OK.

And you could also use the below ways.

(function (){
    alert('a function');
})();

!function (){
    alert('a function');
}();

+function (){
    alert('a function');
}();

Upvotes: 1

Related Questions