简体   繁体   中英

Function accessing itself when name is overwritten by argument

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?]

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.

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));
  • A function named f in the global scope (accessible using window.f )
  • A parameter to the global function named 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.

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 ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM