【问题标题】:Why is context inside non-interactive Function object different in node.js?为什么 node.js 中非交互式函数对象内的上下文不同?
【发布时间】:2012-09-04 12:04:01
【问题描述】:

我想从需要另一个模块的字符串创建一个函数(不要问)。

当我尝试在节点交互式 shell 中执行此操作时,一切都很好而且花花公子:

> f = new Function("return require('crypto')");
[Function]
> f.call()
{ Credentials: [Function: Credentials],
  (...)
  prng: [Function] }

但是,当我将完全相同的代码放入文件时,我被告知 require 函数不可用:

israfel:apiary almad$ node test.coffee 

undefined:2
return require('crypto')
       ^
ReferenceError: require is not defined
    at eval at <anonymous> (/tmp/test.coffee:1:67)
    at Object.<anonymous> (/tmp/test.coffee:2:3)
    at Module._compile (module.js:446:26)
    at Object..js (module.js:464:10)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Array.0 (module.js:484:10)
    at EventEmitter._tickCallback (node.js:190:38)

如何解决?

此外,它告诉我我对 node.js 上下文/范围一无所知。那是什么?

【问题讨论】:

    标签: javascript node.js eval require anonymous-function


    【解决方案1】:

    问题在于范围。

    new Function() 的参数正在全局范围内进行评估。然而,Node 仅将 require 定义为其交互模式/shell 的全局变量。否则,它将执行closure 中的每个模块,其中requiremoduleexports 等被定义为局部变量。

    因此,要定义函数以使 require 在范围内 (closure),您必须使用 function operator/keyword

    f = function () { return require('crypto'); }
    

    或者,CoffeeScript 中的 -&gt; operator

    f = -> require 'crypto'
    

    【讨论】:

    • 那么没有办法在全局范围内执行Function实例?
    • @Almad 您可以定义对函数f 的全局引用。但是,函数的主体必须在闭包内进行评估,以使require 在范围内。
    猜你喜欢
    • 2020-02-23
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多