深入理解nodejs 中 exports與module.exports,nodejsexports

來源:互聯網
上載者:User

深入理解nodejs 中 exports與module.exports,nodejsexports

在Javascript 中,有2種範圍,分為 全域範圍 ,和函數範圍,

在 瀏覽器端 , 全域範圍 就是 window對象的屬性,

函數範圍 就是 ,某個 函數 產生的對象的屬性;

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <script>        var name = 'html5';        function Obj(){            this.name = 'CSS3';        }        var obj = new Obj();        console.log(obj);        console.log(window.name);    </script></head><body></body></html>

上面是代碼的運行結果,在使用this 的 時候,要特別注意,因為this 是 在運行時 ,動態綁定某個對象,有諸多的不確定性,可能會產生意想不到的結果。


在nodejs 中,也有2 種範圍,分為 全域範圍 ,和模組範圍,我們一探究竟,將下面儲存成test1.js,運行

var name = 'var-name';name = 'name';global.name='global-name';this.name = 'module-name';console.log(global.name);console.log(this.name);console.log(name);

我們看到 var name = 'var-name';name = 'name';  是定義的局部變數;

而 global.name='global-name'; 是為 全域對象定義一個name 屬性,

而 this.name = 'module-name'; 是為模組對象定義了一個name 屬性


那麼我們來驗證一下,將下面儲存成test2.js,運行

var t1 = require('./test1');console.log(t1.name);console.log(global.name);


從結果可以看出,我們成功匯入 了test1 模組,並運行了 test1的代碼,因為在test2 中 輸出 了 global.name,

而 t1.name 則是 test1 模組中通過 this.name 定義的,說明this 指向 的是 模組範圍對象。


好吧,我們先來聊一下 CommonJS ,再來 接下來的猜想,

根據CommonJS規範,一個單獨的檔案就是一個模組。載入模組使用require方法,該方法讀取一個檔案並執行,最後返迴文件內部的exports對象。


那麼我們來看看在node模組中 exports、module.exports、this

console.log(module.exports === this);console.log(module.exports === exports);console.log(this === exports);


從上面代碼執行結果可以看出, 他們都指向同一個對象,

那到底有什麼區別,為什麼要這麼設計,有什麼好處,

我們以後來分析,請繼續關注。。。


nodejs開發指南中MircoBlog例子中遇到的問題

去 cnodejs.org/ 提問吧 那人多
 
Nodejs Express420 怎更改成post

router.get('/', 添加判斷: if( req.method == 'post' )
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.