1. 程式人生 > >Nodejs:模組的呼叫

Nodejs:模組的呼叫

User.js

//構造方法
function User(id, name, age) {
	this.id = id;
	this.name = name;
	this.age = age;
	this.enter = function () {
		console.log(this.name + "進入國家圖書館");
	}
}
/*
function User() {
	this.id;
	this.name;
	this.age;
	this.enter = function() {
		console.log(this.name + "進入圖書館");
	}
}
*/
module.exports = User;

Teacher.js

var User = require('./User');

function Teacher(id, name, age) {
	User.apply(this, [id, name, age]);//類的繼承
	this.teach = function(res) {
		res.write(this.name + "講課");
	}
}
module.exports = Teacher;

modalcall_1.js

//----------------------n3_modalcall.js模組的呼叫-------------  
var http = require('http');
var User = require('./model/User');
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, "jack", 20);
		//user.id = 1;
		//user.name = "張三";
		//user.age = 20;
		user.enter();
		response.end('');
	}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

modalcall_2.js

//----------------------n3_modalcall.js-------------  
var http = require('http');
var Teacher = require('./model/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, "JackLi", 20);
		teacher.enter();
		teacher.teach(response);
		response.end('');
	}
}).listen(8000);
console.log('Server        running        at        http://127.0.0.1:8000/');