Reputation: 43647
I would like to have a function, which would be accessible to call it by other functions and should self execute when declared.
Like:
function some(var_one, var_two)
{
// do something
}(var_one, var_two); // declare and execute (doesn't work)
function add_pair()
{
// do something
some(James, Amber);
}
What is a proper syntax to do this?
Upvotes: 4
Views: 230
Reputation: 165971
You cannot invoke a function declaration. The pair of parentheses following the declaration will do nothing at all. You could do something like this:
var some;
(some = function (var_one, var_two) {
console.log(var_one, var_two);
})("a", "b");
some("b", "c");
The above example will log "a, b", followed by "b, c". But that looks a bit messy. You could just stick with what you have and call the function like normal:
function some(var_one, var_two) {
console.log(var_one, var_two);
}
some("a", "b");
Update
Note that by changing the function declaration to an expression (which is what happens in my first example above) you remove the ability to call the function before it appears to be declared in the source, since declarations are hoisted to the top of the scope in which they appear, and assignments happen in place. With a function declaration, the following example works perfectly:
some("a", "b"); // Call it before it appears to be declared
function some(var_one, var_two) {
console.log(var_one, var_two);
}
I really can't see any reason why you would need to combine the declaration and invocation into one.
Upvotes: 5
Reputation: 664579
No, you can't declare and execute the same time (unless in IE, creating two different functions). Have a look at http://kangax.github.com/nfe/
If your function has no return value, you could exploit that and let the function return itself, making it an immediately-executed-named-function-expression which is assigned to a variable:
var someGlobal = (function some(args) {
// do something
return some;
})(now_args);
// then
someGlobal(James, Amber);
Better use a declaration and an invocation, to make things clearer.
Upvotes: 0