【发布时间】:2019-01-17 00:00:20
【问题描述】:
我是 Javascript 和 NodeJS 的新手,我正在尝试了解 module.exports 的工作原理。
// exports.js
module.exports = "abc";
module.exports.b = function() {
console.log("b");
};
当我需要包含上述代码的文件时,使用:
const exportsEg = require('./exports');
console.log(exportsEg);
exportsEg.b(); // TypeError: exportsEg.b is not a function
但是,当我在exports.js 中使用以下行时,exportsEg.b() 不会抛出任何错误:
module.exports = new String("abc");
据我了解,字符串文字在 Javascript 中也是对象。当我将 module.exports 分配给 String 文字对象时,它不能保存任何其他属性,因此当我们尝试访问函数 b 时出现错误。但是为什么将 module.exports 分配给一个新的 String 对象时,我们不会得到同样的错误呢?
【问题讨论】:
标签: javascript node.js