当通过设置动态运行代码(例如eval及其使用nodejs的朋友)时,我们遇到了使用此代码段演示的一个特殊问题
console.log("typeof require: " + typeof require);
var func = new Function('console.log("typeof require: " + typeof require);');
func();
global.require = require;
func();
然后输出:
typeof require: function
typeof require: undefined
typeof require: function
因此,在执行使用Function构造函数创建的函数时,似乎需要(正如我所理解的那样始终是全局对象的一部分)。除非它明确地设置为节点中的全局对象。
同样不适用于控制台等。
在上下文中require函数是否不同?
修改
好的,下面的代码可能会说明发生了什么:
function local() {
}
var func = new Function('console.log("typeof require: " + typeof require); console.log("typeof local: " + typeof local);');
function func2() {
console.log("func2: typeof require: " + typeof require);
console.log("func2: typeof local: " + typeof local);
}
func();
func2();
global.require = require;
func();
如评论中所述,require被注入执行模块。因此它只对同一模块中定义的其他函数可见,与模块本地函数的方式大致相同。
这在功能对象的MDN documentation中进行了解释。
虽然你可以检查nodejs REPL中的全局对象,并且require似乎是全局对象的一部分,但它很奇怪:
$ node
> global
{ global: [Circular],
process:
process {
...
'/home/node_modules',
'/node_modules' ] },
require:
{ [Function: require]
resolve: [Function],
main: undefined,
extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
registerExtension: [Function],
cache: {} },
_: [Circular] }
但是从文件执行时,以下代码段显示未定义:
console.log("typeof global.require: " + typeof global.require);
虽然在REPL中执行时,它的行为有所不同:
> Function('console.log("typeof require: " + typeof require);')()
typeof require: function