在node中的模块,相当于java中的类,模块包含成员变量,成员方法,继承 在下面设计一个user,一个子类tec
//这个类在外部的node1.js文件中
function user(id,name,age){
//第一种写法
this.id=id;
this.name=name;
this.age=age;
//第二种写法
this.id;
this.name;
this.age;
this.enter=function(){ //成员方法
console.log('名字'+this.name);
}
}
module.exports=user;//先导出
tec相当于user的子类,可以继承user中的方法:
var user=require('./node1');
//继承user。在这里文件的名字可以写后缀.js,也可以不写
function tec(id,name,age){
user.apply(this,[id,name,age]);
this.ter=function(res){ //成员方法
res.write(this.name+'讲课');
}
}
module.exports=tec;//先导出
node调用时的文件:
var http = require('http');
var user=require("./node1");//导入外部的类
var tec=require("./tec");//导入外部的类
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){ //避免两次运行
User=new user(1,'张三',20);
Tec=new tec(2,'李四',25); //将对象实例化 //使用了第一种方法
/* User.id=1;
User.name="张三";
User.age=20;*/
User.enter(); //如果上面user中使用第二种方法的时候需要用这一段
Tec.enter();
Tec.ter(response);
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/'); //写一个运行的地址
本人node初级, 如果有错误欢迎指出!互相学习!不喜勿喷。