为什么 module.exports 可以保存字符串对象和模块实例,但不能保存字符串文本和模块实例



我是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 中使用以下行时,exportEg.b() 不会抛出任何错误:

module.exports = new String("abc");

根据我的理解,字符串文字在Javascript中也是对象。当我将 module.exports 分配给字符串文本对象时,它不能保存任何其他属性,因此当我们尝试访问函数 b 时会出现错误。但是,为什么当 module.exports 分配给一个新的字符串对象时,我们没有得到同样的错误呢?

考虑使用严格模式及早检测错误 - 有了它,您的代码会导致

未捕获的类型错误:无法在字符串"abc"上创建属性"b"

'use strict';
const module = {};
module.exports = "abc";
module.exports.b = function() {
    console.log("b");
};

在草率模式下,属性分配将以静默方式失败。

请单独导出字符串和函数。

module.exports = {
  fn: function() { console.log('b'); },
  str: 'abc'
};

只是为了扩展一些要点,这里有一些关于module.export如何工作的澄清。

var module = {
 exports: {},
};
// Previously module.exports was an object, now it's a string 
// primitive, therefore cannot have properties assigned to it.
module.exports = "abc";
console.log(typeof module.exports)
// Calling new String However returns an object, which can be assigned new
// properties, which is why it worked
module.exports = new String('abc')
console.log(typeof module.exports);

字符串覆盖 exports 对象,则将该字符串用作对象为其分配函数。 我推荐以下方法

module.exports.a = "abc";
module.exports.b = function() {
    console.log("b");
};

字符串文本的类型为 stringnew String()的类型为 object 。它们不完全是一回事。JS中任何类型的对象都可以设置新属性;基元不能。自己测试一下:输出typeof "Something",它会说它是一个字符串;但是输出typeof new String("Something")它会说它是一个对象。

最新更新