記錄module.exports 與 exports使用

1 exports是module.exports的一個引用

2 require引用模塊後,返回給調用者的是module.exports而不是exports

3 exports.xxx,相當於在導出對象上掛屬性,該屬性對調用模塊直接可見

4 exports =相當於給exports對象重新賦值,調用模塊不能訪問exports對象及其屬性

如果此模塊是一個類,就應該直接賦值module.exports,這樣調用者就是一個類構造器,可以直接new實例


1 exports暴露屬性和函數:

exports.str = 'a';
exports.fn = function () { wx.showToast({
  title: 'good',
})}; 
在使用時候: var m=require("../../utils/demo.js");直接m.str或m.fn()就能引用暴露的屬性和方法


2 module.exports暴露對象

var handle;
handle = {
  str:"hello_world",
  fn: function () {
    wx.showToast({
      title: 'hello_world',
    })
  }
}
module.exports = handle;
在使用時候:var m = require("../../utils/hhh.js");m對象就持有暴露的handle對象引用,用m.fn()調用函數,m.str引用str屬性


注意:

1 對於要導出的屬性,可以簡單直接掛到exports對象上


2 對於類,爲了直接使導出的內容作爲類的構造器可以讓調用者使用new操作符創建實例對象,應該把構造函數掛到module.exports對象上,不要和導出屬性值混在一起


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章