为什么 node.js 中非交互式 Function 对象内的上下文不同? [英] Why is context inside non-interactive Function object different in node.js?

查看:24
本文介绍了为什么 node.js 中非交互式 Function 对象内的上下文不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to create a function from string that requires another module (don't ask).

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

When I try to do that in node interactive shell, everything is fine and dandy:

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

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

However, when I put the exact same code in file, I am told that require function is not avaliable:

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 上下文/范围一无所知.那是什么?

Also, it tells me I do not know something about node.js contexts/scopes. What is that?

推荐答案

问题在于范围.

new Function() 的参数正在全局范围内求值.但是,Node 仅将 require 定义为其交互模式/shell 的全局变量.否则,它会在 closure 中执行每个模块,其中 requiremoduleexports等被定义为局部变量.

The argument to new Function() is being evaluated in the global scope. Node, however, only defines require as a global for its interactive mode/shell. Otherwise, it executes each module within a closure where require, module, exports, etc. are defined as local variables.

因此,定义函数以便 require 在范围内 (closure),你必须使用 function 运算符/关键字:

So, to define the function so that require is in scope (closure), you'll have to use the function operator/keyword:

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

或者,CoffeeScript 中的 -> 运算符:

Or, the -> operator in CoffeeScript:

f = -> require 'crypto'

这篇关于为什么 node.js 中非交互式 Function 对象内的上下文不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆