module.exports 和 exports的區別

 

引用傳遞的理解 就理解了這二者的區別

   var arr = [10,20,30];
    var newarr = arr;

    console.log(arr);//[10,20,30]
    console.log(newarr);//[10,20,30];

    
    newarr[0] = 40;
    console.log(arr);//[40,20,30];
    console.log(newarr);//[40,20,30];

 

  

 

 

例一. 採用module.exports

module.exports = {
    hello: "hello",
    world: "world"
};

例二. 採用exports

exports.hello = "hello";
exports.world= "world";

  

   區別   

exports = {
    hello: "hello",
    world: "world"
};//這樣代碼不報錯, 可是沒有用, 接口並未暴露出來. 緣由請看下面

  

var load = function (exports, module) {
    // .js的文件內容
    ...
    // load函數返回:
    return module.exports;
};

var exported = load(module.exports, module);

  

 

系統自動給nodejs 文件增長2個變量 exports 和 module, module 又有一個屬性 exports, 這個exports 屬性指向一個空對象 {}; 同時 exports這個變量也指向了這個空對象{};node

因而就有了 exports => {} <=module.exports.

瀏覽器

 

就是說本身定義一個exports沒有用的,必須給modul。exports設置key:value值(exports.text= "hello")才能夠,由於最後是導出 module.exports。函數

(外加:node.js是遵循common.js 實用const ** = require("**") 和 module.exports暴露模塊,而瀏覽器v8引擎是解析js腳本文件的,並不能運行node.js的模塊。ui

 

推薦用module.exports導出。spa

相關文章
相關標籤/搜索