我正在尝试从JavaScript: The Definitive Guide 6th ed.学习JavaScript第81页,作者解释说,如果您使用原始名称调用eval
,而不是创建其他名称时,则会有所不同。作者用以下源代码说明:
var geval = eval; // Using another name does a global eval
var x = "global", y = "global"; // Two global variables
function f() // This function does a local eval
{
var x = "local"; // Define a local variable
eval("x += 'changed';"); // Direct eval sets local variable
return x; // Return changed local variable
}
function g() // This function does a global eval
{
var y = "local"; // A local variable
geval("y += 'changed';"); // Indirect eval sets global variable
return y; // Return unchanged local variable
}
console.log(f(), x); // Local variable changed: prints "localchanged global":
console.log(g(), y); // Global variable changed: prints "local globalchanged":
我尝试执行代码,然后得到:
/usr/bin/node test.js
localchanged global
undefined:1
y += 'changed';
^
ReferenceError: y is not defined
at eval (eval at g (/home/martin/Projects/WebPages/test.js:18:5), <anonymous>:1:1)
at eval (native)
at g (/home/martin/Projects/WebPages/test.js:18:5)
at Object.<anonymous> (/home/martin/Projects/WebPages/test.js:23:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
Process finished with exit code 8
请您解释为什么在y
的来电中看不到geval
变量?