@breakerthb
2016-07-11T06:36:52.000000Z
字数 683
阅读 1218
NodeJS
模块公开接口,相当于Java中的public
从外部获取一个模块接口(这个接口是在另一个文件中用exports声明的)
用exports关键字将函数声明为公用。
-文件:hello.js
// hello.js
exports.world = function()
{
console.log('Hello World!');
}
用require关键字引入。
文件main.js
// main.js
var hello = require('./hello');
hello.world();
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();