1、新建调用的js
第一种调用没有初始值的模块
var http = require('http'); var User = require('./module/User');//引入的是user模块 不是user.js http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'}); if(request.url!=="/favicon.ico"){ //清除第2此访问 user = new User(); //实例化这个模块 user.id = 1; user.name = "张三"; user.age = 20; user.enter(); response.end(''); } }).listen(8888); console.log('Server running at http://127.0.0.1:8888/');
function User(){ this.id; this.name; this.age; this.enter = function(){ console.log('我叫'+this.name+',我的年龄是'+this.age); } } module.exports = User;//导出这个模块/类,让其他js能引入
第二种调用初始值的模块
var http = require('http'); var User = require('./module/User');//引入的是user模块 不是user.js http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'}); if(request.url!=="/favicon.ico"){ //清除第2此访问 user = new User(1,"zhangsan",20); //实例化这个模块 user.enter();//执行方法 response.end(''); } }).listen(8888); console.log('Server running at http://127.0.0.1:8888/');
function User(id,name,age){ this.id = id; this.name = name; this.age = age; this.enter = function(){ console.log('我叫'+this.name+',我的年龄是'+this.age); } } module.exports = User;//导出这个模块/类,让其他js能引入
2、一个模块继承另一个模块,然后调用
调用的js
var http = require('http'); var Teacher = require('./module/Teacher'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'}); if(request.url!=="/favicon.ico"){ //清除第2此访问 teacher = new Teacher(1,"zhangsan",20); teacher.enter();//对父类的方法调用 teacher.teach(response);//调用自己的方法 response.end(''); } }).listen(8888); console.log('Server running at http://127.0.0.1:8888/');
User类
function User(id,name,age){ this.id = id; this.name = name; this.age = age; this.enter = function(){ console.log('我叫'+this.name+',我的年龄是'+this.age); } } module.exports = User;//导出这个模块/类,让其他js能引入
Teacher类 并且继承User类
var User = reqire('./User'); function Teacher(id,name,age){ User.apply(this,[id,name,age]);//这句话实现了继承User这个模块,并且初始化,里面的id,name,age 就是Teacher(id,name,age)里面传进来的 this.teach = function(res){ res.write(this.name+"讲课"); } } module.exports = Teacher;//导出这个模块/类,让其他js能引入