模块(类)定义文件的语法
function className(params){ //模块(类)定义文件: 构造函数
this.属性1, this.属性n,
this.funNameA=function(){...},
this.funNameN=function(){...}
}
module.exports=className; //模块(类)定义文件: 申明构造函数可被调用
模块(类)构造函数定义以逗号(,)/分号(;)分隔各属性及方法
nodejs无须prototype关键字, 直接定义方法即可达到重复使用效果/效率
原生JavaScript的方法定义以prototype限定达到函数重用率,否则资源浪费
// d06_User.js
function User(id, name, age){ //构造函数申明
this.id=id,
this.name=name,
this.age=age,
this.enter=function(){
console.log(this.name+'进入图书馆');
}
}
module.exports=User; // 申明构造函数可被调用
模块(类)调用文件的语法
var className=require(‘url’); //模块(类)调用文件:导入申明;
var objectName=new className(params); //模块(类)调用文件: 对象实例化;
objectName.funNameN(); //模块(类)调用文件: 对象/类的方法调用
// d06_modelcall.js
var http=require('http');
var People=require('./models/d06_User'); //外部函数导入; 可省略后缀
http.createServer(function(request, response){
response.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
if(request.url!=='/favicon.ico'){ //清除2次访问
var pepA=new People('001', '张三', 33);
var pepB=new People('002', '李四', 44);
var fA=pepA.enter(); //输出: 张三进入图书馆
var fB=pepB.enter(); //输出: 李四进入图书馆
console.log(fA==fB); //输出: true
response.end(''); //不可省略
}
}).listen(8000); //监听端口
console.log('Server running at http://127.0.0.1:8000/');
console.log(fA==fB)输出true:说明User的enter()方法被重复调用,而未新创建