我是 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 分配给一个字符串文字对象时,它不能包含任何其他属性,因此当我们尝试访问函数 b 时会出现错误。但是,当 module.exports 被分配给一个新的 String 对象时,为什么我们没有得到同样的错误呢?
最佳答案
考虑使用严格模式尽早检测错误 - 有了它,您的代码会产生结果
Uncaught TypeError: Cannot create property 'b' on string 'abc'
'use strict';
const module = {};
module.exports = "abc";
module.exports.b = function() {
console.log("b");
};
在草率模式下,属性分配将默默地失败。
改为单独导出字符串和函数。
module.exports = {
fn: function() { console.log('b'); },
str: 'abc'
};
关于javascript - 为什么 module.exports 可以保存一个 String 对象和一个模块实例,而不是一个 String 文字和一个模块实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54210674/