Node.js调用模块
User.js
function User(){
this.id;
this.name;
this.age;
this.enter = function(){
console.log(this.name + " 进入图书馆");
};
}
module.exports = User;
var http = require('http');
var User = require('./User');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type' : 'text/html; charset=utf-8'});
if(req.url !== "/favicon.ico"){
res.write('<h1>Node.js</h1>');
console.log("running...");
var user = new User();
user.name = "张三";
user.age = 20;
user.id = 1;
user.enter();
res.end('<p>Hello World!!</p>');
}
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
运行结果:
改进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 http = require('http');
var User = require('./User');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type' : 'text/html; charset=utf-8'});
if(req.url !== "/favicon.ico"){
res.write('<h1>Node.js</h1>');
console.log("running...");
var user = new User(1,"李四",20);
user.enter();
res.end('<p>Hello World!!</p>');
}
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
创建User的子类:Teacher.js
var User = require('./User');
function Teacher(id,name,age){
User.apply(this,[id,name,age]);//应用,继承User父类
this.teach = function(res){
console.log("teach");
res.write(this.name + "讲课");
};
}
module.exports = Teacher;
var http = require('http');
var Teacher = require('./Teacher');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type' : 'text/html; charset=utf-8'});
if(req.url !== "/favicon.ico"){
res.write('<h1>Node.js</h1>');
console.log("running...");
var teacher = new Teacher("1","蔡老师",28);
teacher.enter();
teacher.teach(res);
res.end('<p>Hello World!!</p>');
}
}).listen(3000);
console.log("HTTP server is listening at port 3000.");