【问题标题】:Indirect call to eval in strict mode. What happens to x?在严格模式下间接调用 eval。 x 会发生什么?
【发布时间】:2016-04-13 16:30:46
【问题描述】:

我一直在为求职面试而学习,并开始深入研究 JavaScript。想出了这个。

所以:

"use strict";

var x = 0;
var y = 0;

eval("x=3;y=11;"); //direct call to eval in global scope

console.log("x: " + x); // outputs 3
console.log("y: " + y); // outputs 11

但是:

"use strict";

var x = 0;

(0, eval)("x=3;y=11;"); //indirect call to eval in global scope

console.log("x: " + x); // outputs 0 because the strict mode won't allow the reassignment? 
console.log("y: " + y); // outputs 11

我不知道/理解执行 eval 时 x 会发生什么。我知道在严格模式下,分配没有问题。有人愿意向我解释这个吗?谢谢!

【问题讨论】:

  • 它在我的控制台中为我打印 3。
  • ^ 相同。你在什么环境下运行这段代码?
  • 两个代码部分对我来说都是一样的
  • 我是用node来执行文件的。
  • In what scope are module variables stored in node.js? 的可能重复项使用全局变量重试。

标签: javascript scope eval strict


【解决方案1】:

这似乎是 Node.js 处理变量的方式(它们不默认为全局变量)。对 eval 的间接调用是分配给全局对象。

"use strict";

var x = 0;

(0,eval)("x=3;y=11;");
x++;
console.log("x: " + x); // outputs 1
console.log("global x: " + global.x);  // outputs 3
console.log("y: " + y); // outputs 11

【讨论】:

  • 这似乎是节点中的那些变量不是全局的 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2011-05-18
  • 2012-05-18
  • 2012-09-16
  • 1970-01-01
  • 2011-01-25
相关资源
最近更新 更多