【发布时间】:2012-08-21 00:55:06
【问题描述】:
有人可以帮我理解以下行为吗?我希望,因为我可以在此回调中设置全局f,我也应该能够更改它。我不太了解节点如何在 REPL 中处理上下文与全局,无法理解这一点,我将不胜感激。
在没有 useGlobal 的情况下启动 REPL
$ cat test.js
var repl = require('repl');
repl.start({useGlobal:false});
现在尝试连续设置两次f:
$ node test.js
> f
ReferenceError: f is not defined
> setTimeout(function(){f=1;}, 0);
> f
1
第一次工作......现在再试一次:
> setTimeout(function(){f=2;}, 0);
> f
1
嗯!
第一次运行设置它;第二个不影响它。
(设置useGlobal:true 我得到了我期望的行为。)
【问题讨论】:
-
请注意:延迟 > 0 时也存在问题,匿名函数不存在:
!function() { f = 2}();按预期工作。我不知道......也许是一个错误? -
我认为“this”developer.mozilla.org/en-US/docs/DOM/…对“this”问题有一些影响:)
-
@chumkiu 代码中没有使用关键字“this”。为什么要对上述问题负责?
-
@Javaguru 是的,但
useGlobal if set to true , then the repl will use the global object, instead of running scripts in a separate context.选项我想它与this有关(可能是低级错误)
标签: javascript node.js scope global read-eval-print-loop