Node 模塊

Node.js 是什么?

Node.js? is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Current Version: v0.10.33

為什么要有 Node 模塊?

模塊,是 Node 讓代碼易于重用的一種組織和包裝方式

模塊創(chuàng)建流程

創(chuàng)建模塊

var a = 'a';
function A() {
    console.log(a);
}
exports.printA = A;

引入模塊

var a = require('./module_');
a.printA();

模塊暴露構(gòu)造函數(shù)

//定義
var B = function (input) {
    this.input = input;
}
B.prototype.printB = function () {
    console.log(this.input);
}
module.exports = exports = B;

//調(diào)用
var B = require('./module_');
var b = new B('asdf');
b.printB();
  • exports
     只是對(duì) module.exports 的一個(gè)全局引用,最初被定義為一個(gè)可以添加屬性的空對(duì)象
  • exports.printA
     是 module.exports.printA 的簡(jiǎn)寫(xiě)
  • exports = B
     將會(huì)打破 module.exports 和 exports 之間的引用關(guān)系
  • module.exports = exports
     可以修復(fù)鏈接

Monkey Patching

Node 將模塊作為對(duì)象緩存起來(lái)
 第一個(gè)文件會(huì)將模塊返回的數(shù)據(jù)存到程序的內(nèi)存中,第二個(gè)文件就不用再去訪問(wèn)和計(jì)算模塊的源文件了
 并且第二次引入有機(jī)會(huì)修改緩存的數(shù)據(jù)

歡迎直接訪問(wèn)我的個(gè)人博客,閱讀效果更佳:https://yuzhouwan.com/posts/23363/

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容