使用 ES6 import/export 时 nodejs 中 'this' 的含义
Meaning of 'this' in nodejs when using ES6 import/export
我有一个 javascript 文件
- 当我使用 es6 import/export 并做
console.log(this); // undefined
它给出未定义。
- 当我使用 require/module.exports
执行相同的操作时
console.log(this); // {}
它给出了一个空的 module.exports 对象。
我的问题是 - 为什么它在 es6 import/export.
的情况下给出未定义
在 ES6 模块中(使用 export
和 import
声明),this
关键字默认值为 undefined
- 没有合理的对象应该引用到。这也让我们认识到更多的错误,你不小心引用了模块的 this
(例如,在对象字面量中写了一个箭头函数)但本意是动态的 this
或其他东西 - 的代码在访问 undefined
上的 属性 时中断,而不是访问其他对象上的 属性。
如果要从模块引用全局对象,请显式使用 globalThis
。
在 CommonJS 模块中(使用 module.exports
和 require()
),它引用模块对象 - 参见 What does "this" mean in a nodejs module? or Meaning of "this" in node.js modules and functions.
我有一个 javascript 文件
- 当我使用 es6 import/export 并做
console.log(this); // undefined
它给出未定义。
- 当我使用 require/module.exports 执行相同的操作时
console.log(this); // {}
它给出了一个空的 module.exports 对象。
我的问题是 - 为什么它在 es6 import/export.
的情况下给出未定义在 ES6 模块中(使用 export
和 import
声明),this
关键字默认值为 undefined
- 没有合理的对象应该引用到。这也让我们认识到更多的错误,你不小心引用了模块的 this
(例如,在对象字面量中写了一个箭头函数)但本意是动态的 this
或其他东西 - 的代码在访问 undefined
上的 属性 时中断,而不是访问其他对象上的 属性。
如果要从模块引用全局对象,请显式使用 globalThis
。
在 CommonJS 模块中(使用 module.exports
和 require()
),它引用模块对象 - 参见 What does "this" mean in a nodejs module? or Meaning of "this" in node.js modules and functions.