I have the following line of code:
(function f() {});
Is there a way we can reference f() outside of the grouping?
I have the following line of code:
(function f() {});
Is there a way we can reference f() outside of the grouping?
感谢 javascript 的泄漏分配,你总是可以得到(几乎)任何表达式的值:
(function f() {}).valueOf() // == function f() {}
(function f() {}).prototype.constructor
Esailija's answer is innovative but it misses the point. For example if you're using the function expression as follows then using .prototype.constructor
makes no sense:
window.addEventListener("DOMContentLoaded", (function f() {}), false);
In such a case I prefer making the function expression a function declaration instead and replacing the expression with the function name:
window.addEventListener("DOMContentLoaded", (f), false);
function f() {}
The above program is perfectly valid. You can call a function declaration before it appears in the program. Now you can reference f
"outside of its grouping". It's kind of like cheating but then again this is the way people normally do it (minus the unnecessary parentheses).