2

I have the following line of code:

(function f() {});

Is there a way we can reference f() outside of the grouping?

4

3 回答 3

2

感谢 javascript 的泄漏分配,你总是可以得到(几乎)任何表达式的值:

 (function f() {}).valueOf() // == function f() {}
于 2013-07-10T16:28:25.887 回答
2

(function f() {}).prototype.constructor

于 2013-07-10T16:20:40.807 回答
1

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

于 2013-07-10T16:42:28.850 回答