Reputation: 116343
How does JavaScript deal with functions with names ending with ()
? Consider for example the following piece of code:
var foo() = function () { }; // The empty function
var bar = function(foo) { var myVariable = foo(); };
It seems like there are two possible interpretations for what foo();
means:
foo
. This assigns myVariable
the returned value of foo
.foo()
as the name of the function defined at first. This assigns myVariable
the empty function.Is this even legal code? If so, what are the rules?
Upvotes: 2
Views: 223
Reputation: 1039110
Is this even legal code?
No:
var foo() = function () { };
should be:
var foo = function () { };
If so, what are the rules?
In this case the foo
argument will have precedence because it is defined in an inner scope than the foo
function. So it's really a matter of scope: where is the variable defined. The interpreter first starts by looking in the innermost scope of the code, then in the outer, ... until it reaches the global scope (the window object).
So for example the result of the following code will be 123
as seen in this live demo:
var foo = function () { alert('we are in the foo function'); };
var bar = function(foo) { var myVariable = foo(); alert(myVariable); };
bar(function() { return 123; });
Upvotes: 5
Reputation: 7282
Do you really mean "Can I pass functions as references?" If so, then the answer is yes:
var foo = function() { return 2; }
var bar = function(fn){ return fn(); }
var two = bar(foo);
Upvotes: 0
Reputation: 46637
Identifiers may not contain any parentheses, so the first statement is illegal. The second, however, is fine, myVariable = foo()
executes the foo
parameter and assigns the return value.
Upvotes: 0
Reputation: 84180
In javascript, brackets mean execute. So your code will fail as it will be looking for a function foo on the first line.
Upvotes: 1
Reputation: 185962
The ()
isn't considered part of the name. You'll probably get a syntax error. You can find some naming rules here.
Upvotes: 2