模块和包

模块和包

nodejs提供了exports和require两个对象,其中exports是模块公开的接口,require用于从外部获取一个模块的接口,即获取模块的exports对象。

function hello() {
    var name;
    this.name = function (thyname) {
        name = thyname;
    };
    this.sayHello = function () {
        console.log('hello' + name);
    };
}
exports.Hello = hello;
//看这里哈
//那就是别个引用我的上面的hello,要这样咩
//require(./untils).Hello //就得到了hello
function hello(){
    var name;
    this.setName = function (thyname) {
        name = thyname;
    };
    
    this.sayHello = function () {
        console.log('hello'+name);
    }
}
module.exports= hello;
//别个引用
var a = require('./untils'); //untils是写有hello对象的文件名字,此时a就相当于hello对象
var b = new a();
//然后就可以用对象的方法啦
b.setName('hhm'); 

看上面两段代码的区别,来总结一下:

. 注意:模块接口的唯一变化:使用module.exports代替了exports.x。其实在外部引入该模块的时候,其接口对象就是要输出的hello对象本身,而不是exports.

. exports本身就仅仅是一个普通的空对象{},专门用来声明接口,所以可以用其他的东西来替代。


文章参考来源:node.js开发指南

posted @ 2016-12-30 17:36  小敏菇凉  Views(105)  Comments(0Edit  收藏  举报