1.开始
Node.js:https://nodejs.org
2.Moudle
js编程中,由于大家可以直接在全局作用域中编写代码,使开发人员可以很容易的新建一个全局变量或这全局模块,这些全局变量或全局模块在工程化的开发中,极易互相冲突,同时也很难搞清楚它们之间互相的依赖关系。Node.js采用CommonJS规范来定义模块与使用模块,提供了required和module.exports来解决这个问题。
required()方法,通过required方法将其他模块引用到当前作用域内。
module.exports方法,从当前作用域中导出对象Object或类定义Function。
定义一个Module,仅包含静态方法
circle.js
:提供了两个方法
area() 求面积,circumference()求周长
1 2 3 4 5 | const PI = Math.PI;
exports.area = (r) => PI * r * r;
exports.circumference = (r) => 2 * PI * r;
|
调用这个Module app.js
:
1 2 | const circle = require( './circle.js' );
console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);
|
上面的示例代码定义一个Module=.Net中包含静态方法的静态类。
定义一个Module,表示普通类
user.js:定义一个User类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 'use strict' ;
const util = require( 'util' );
function User(sId, sName) {
this .Id = sId;
this .Name = sName;
}
User.prototype.toString = function () {
return util.format( " , Name='%s'" , this .Id, this .Name);
}
module.exports = User;
|
app.js:
1 2 3 4 5 6 7 8 9 10 11 | var User = require( './user' );
var pSource = [];
pSource.push( new User( 'liubei' , '刘备' ));
pSource.push( new User( 'guanyu' , '关羽' ));
pSource.push( new User( 'zhangfei' , '张飞' ));
for ( var index = 0; index < pSource.length; index++) {
var element = pSource[index];
console.log( `${element.toString()}`);
}
|
console
1 2 3 | bash string">'liubei' , Name= '刘备'
bash string">'guanyu' , Name= '关羽'
bash string">'zhangfei' , Name= '张飞'
|
定义一个Module表示全局变量
user.js:使用Count()方法来统计实例化总数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 'use strict' ;
const util = require( 'util' );
var nCount = 0;
function User(sId, sName) {
this .Id = sId;
this .Name = sName;
nCount++;
}
User.prototype.toString = function () {
return util.format( " , Name='%s'" , this .Id, this .Name);
}
module.exports = User;
module.exports.Count = function () {
return nCount;
}
|
app.js
1 2 3 4 5 6 7 8 9 10 11 | var User = require( './user' );
var pSource = [];
pSource.push( new User( 'liubei' , '刘备' ));
pSource.push( new User( 'guanyu' , '关羽' ));
pSource.push( new User( 'zhangfei' , '张飞' ));
pSource.forEach( function (pUser) {
console.log( `${pUser.toString()}`);
}, this );
console.log( `count is ${User.Count()}`);
|
console
1 2 3 4 | bash string">'liubei' , Name= '刘备'
bash string">'guanyu' , Name= '关羽'
bash string">'zhangfei' , Name= '张飞'
count is 3
|
http://www.cnblogs.com/mengkzhaoyun/p/5393784.html