node.js調用模塊

一、新建調用的jshtml

第一種調用沒有初始值的模塊app

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能引入

 

第二種調用初始值的模塊ui

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能引入

二、一個模塊繼承另外一個模塊,而後調用this

調用的jsurl

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類spa

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類code

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能引入
相關文章
相關標籤/搜索