簡體   English   中英

為什么module.exports可以包含String對象和模塊實例,但不包含String文字和模塊實例?

[英]Why can module.exports hold a String object and a module instance, but not a String literal and a module instance?

我是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對象時,我們不會得到相同的錯誤?

考慮使用嚴格模式來盡早檢測錯誤 - 用它來代替你的代碼

未捕獲的TypeError:無法在字符串'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'
};

您使用字符串覆蓋exports對象,然后使用該字符串作為對象為其分配函數。 我推薦以下方法

module.exports.a = "abc";

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

只是為了擴展一些要點,這里有一些關於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); 

字符串文字具有類型string new String()具有類型object 它們並不完全相同。 JS中任何類型的對象都可以設置新的屬性; 原始人不能。 自己測試一下:輸出typeof "Something" ,它會說它是一個字符串; 但輸出typeof new String("Something") ,它會說它是一個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM