Reputation: 116333
Normally, a function can access itself like this:
(function f() {
console.log(f); // Prints the function definition
}());
However, when the function f
has an argument also called f
, the argument takes precedence:
(function f(f) {
console.log(f); // Prints 1
}(1));
In the second example, how can I access the function when one of the arguments has the same name as the function?
[Also, where can I find the documentation saying that the argument should take precedence over the function name?]
Upvotes: 4
Views: 110
Reputation: 60414
Regarding:
[Also, where can I find the documentation saying that the argument should take precedence over the function name?]
JavaScript is lexically/statically scoped. The following code contains two identifiers:
(function f(f) {
console.log(f); // Prints 1
}(1));
f
in the global scope (accessible using window.f
)f
that is itself named f
. This parameter is scoped to the function, which is a more-specific scope than the outer scope. In other words, it doesn't take any special rule for the parameter to take precedence; a local/inner/more-specific scope always shadows outer/less-specific scopes.Upvotes: 1
Reputation: 187134
You don't. Just follow this simple rule
Don't shadow (or redeclare in a more specific scope) any variable that you want to use.
Note: arguments.callee
will work for this, but only in some implentations. And it's actually being phased out and is likely to disappear completely in the future.
Upvotes: 4
Reputation: 956
you can use arguments.callee inside the function without using its name.
( function f( f ) {
console.log( f ); // Prints 1
console.log( arguments.callee ); // Prints the function definition
}( 1 ) );
Upvotes: 0