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/