[关闭]
@breakerthb 2016-07-11T06:36:52.000000Z 字数 683 阅读 1134

NodeJS模块系统

NodeJS


模块管理关键字

模块公开接口,相当于Java中的public

从外部获取一个模块接口(这个接口是在另一个文件中用exports声明的)

创建模块

用exports关键字将函数声明为公用。

-文件:hello.js

// hello.js
exports.world = function()
{
    console.log('Hello World!'); 
}

引入模块

用require关键字引入。

BTW: './hello'引入当前目录下的hello.js文件,默认后缀名为js,因此可以省略。

面向对象写法

如何将hello写成一个像类一样的模块,方便在main.js中使用。格式:

module.exports = function() {
// ...
}

类模块

//hello.js 
function Hello() { 
    var name; // 成员变量

    // 成员函数
    this.setName = function(thyName) { 
        name = thyName; 
    }; 
    this.sayHello = function() { 
        console.log('Hello ' + name); 
    }; 
}; 

// 导出
module.exports = Hello;

调用

//main.js 
var Hello = require('./hello'); // 引入Hello类
hello = new Hello(); // 声明对象
hello.setName('BYVoid'); 
hello.sayHello(); 
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注