如果我们在eval(...)
中定义一个function f() { ... }
,为什么它不适用于其余代码,比如#Button3的onClick?
作为比较,如果我们将该函数定义为f = () => { ... };
,则它可用于#Button3的onClick.
为什么这个差异看起来和var functionName = function() {} vs function functionName() {}有点矛盾(这里的概念是function f() { ... }
比f = () => { ... };
的范围更广).
点击1和3(Uncaught ReferenceError: f is not defined
),然后点击2和3(工作中):
document.getElementById('button1').onclick = () => eval("function f() { alert('hello'); }");
document.getElementById('button2').onclick = () => eval("f = () => { alert('hello'); };");
<div id="button1">1 Click me to define f as a function</div>
<div id="button2">2 Click me to define f as a variable function</div>
<div id="button3" onclick="f();">3 Click to run f()</div>