views:

49

answers:

3

hi,

to call a function at the same time it's defined, i had been using:

var newfunc = function() {
    alert('hi');
};
newfunc();

is the following the correct way of combining these 2:

var newfunc = function() {
    alert('hi');
}();
+4  A: 

No. Your second example will immediately call the anonymous function and assign its return value to newfunc.

adamse describes an approach which appears to work. I'd still avoid the approach as the two step process is easier to read and thus will be easier to maintain.

David Dorward
+2  A: 
var newfunc = function f() {
    alert("hi!");
    return f;
}();

Having a named function expressions allows the function to recursively call itself or, in this case, return itself. This function will always return itself, however, which might be an annoyance.

adamse
The problem with this is Internet Explorer's JScript engine behaves differently to the other browsers. In IE, this code creates two variables (and two functions!) in the outer scope - *newfunc* and *f*. In other browsers (and the ECMAScript spec), *newfunc* is created in the outer scope, *f* is available in the inner scope only. This code is potentially dangerous especially when used in the global scope.
Andy E
Further reading on the subject: http://yura.thinkweb2.com/named-function-expressions/#jscript-bugs
Andy E
@Andy: I was aware that IE exhibited strange behaviour with named function expressions however from your link it seems to be a nightmare.
adamse
@adamse: yeah, even I didn't realize that it created two separate functions until I found that reference :-) I hope it's fixed in IE9 (which has an entirely rewritten JavaScript engine).
Andy E
+1  A: 

If I understand your question correctly, give this a try:

(f = function (msg) {
  msg =  msg ? msg : 'default value';
  alert(msg); }
)();


f('I\'m not the default value!');

You'll get two alerts, the first one will say "default value" and the second will say "I'm not the default value. You can see it in action at jsBin. Click 'preview' to make it run.

Erik