【问题标题】:Why can module.exports hold a String object and a module instance, but not a String literal and a module instance?为什么 module.exports 可以保存 String 对象和模块实例,但不能保存 String 文字和模块实例?
【发布时间】: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


    【解决方案1】:

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

    未捕获的类型错误:无法在字符串“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'
    };
    

    【讨论】:

      【解决方案2】:

      只是为了扩展一些观点,这里对 module.exports 的工作原理进行了一些说明。

      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);

      【讨论】:

        【解决方案3】:

        您用字符串覆盖导出对象,然后您将字符串用作对象来为其分配函数。我推荐以下方法

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 2017-02-04
            • 1970-01-01
            • 1970-01-01
            • 2011-09-22
            • 2020-04-05
            • 2018-07-09
            • 1970-01-01
            • 2015-04-03
            • 1970-01-01
            相关资源
            最近更新 更多