Nodejs_day04

Nodejs模块系统

1.如何创建一个模块

创建一个js(hello.js)

exports.world = function(){//为什么可以这么写,因为exports是nodejs公开的借口

  console.log('hello nodejs');

}

使用:

var hello = require('./hello')

hello.world();//打印结果:hello nodejs

有时候我们只想把一个对象封装到模块中,我们可以这么操作

function Hello(){

  var name ;

  this.setName = function(thyname){

    name = thyname;

  }

  this.sayHello = function(){

    console.log('hello '+name);

  }

}

module.exports = Hello;

使用

var Hello = require('./hello');//默认后缀名就是.js

var hello = new Hello();

hello.setName('liyajie');

hello.sayHello();

//结果打印:hello liyajie

原文地址:https://www.cnblogs.com/liyajie/p/4814814.html