TypeError:无法在module.exports中设置未定义的属性

'use strict'; module.exports = function () { this.myVar = 'example'; console.log(this.myVar); }; 

我得到的错误:

 /home/karl/mymodule.js:3 this.myVar = 'example'; ^ TypeError: Cannot set property 'myVar' of undefined 

在严格模式下, thisundefined

但在非严格模式下, this只不过是指向GLOBAL

所以在这里,你试图设置一些undefined ,所以错误

在哪里,你打算附加myVar

在你的module ? 或在GLOBAL ? 如果它的GLOBAL (这实际上是一个坏主意),使用GLOBAL.myVarglobal.myVar

如果它在你的模块上,你可以做module.exports.myVar = 'example';