node.js(二)----调用模块

1.创建一个Person类,Student和Teacher继承Person

    Person:

function Person(name,age,id) {
    this.name = name;
    this.age = age;
    this.id = id;
    this.do = function (res) {
        console.log(this.name+',走了进来');
        res.write(this.name+',走了进来');
    }
}

module.exports = Person;

    Student:

let person = require('./person.js');
function Student(name,age,id) {
    person.call(this,name,age,id);
    this.study = function (res) {
        console.log(this.name+'正在学习');
        res.write(this.name+'正在学习');
    }
}
module.exports = Student;

    Teacher:

let person = require('./person.js');
function Teacher(name,age,id) {
    person.call(this,name,age,id);
   this.teach = function (res) {
       console.log(this.name+'正在上课');
       res.write(this.name+'正在上课');
   }
}
module.exports = Teacher;

2.在创建服务的js文件中调用

const student = require('./student.js');
const teacher = require('./teacher.js');
const http = require('http');  //导入http
const hostname = '192.168.1.108';  //ip地址   随便写   如需要在局域网内,用手机访问,则需要将其设置为电脑的ipv4地址
const port = 3000;  //端口号
const server = http.createServer((req, res) => {   //创建一个server
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/plain;charset = utf-8');
    if (req.url !== '/favicon.ico') {  //清除二次访问
        let s1 = new student('张三',20,333);
        let t1 = new teacher('王老师',35,566);
        s1.do(res);
        t1.do(res);
        s1.study(res);
        t1.teach(res);
        res.end();   //用于关闭连接
    }
});

server.listen(port, hostname, () => {  //监听server
    console.log(`服务器运行在http://${hostname}:${port}/`);
});








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值