zoukankan      html  css  js  c++  java
  • Node.js:模块

    概要本篇博客主要介绍node.js的模块

    1.创建模块

      在node.js中创建一个模块非常简单,因为一个文件就是一个模块。我们只需要明白如何从其他文件中获取这个模块。Node.js提供了 exportsrequire 两个对象,其中exports是模块的公开接口,require用于从外部获取一个模块的接口,即所获取模块的exports对象。看下面的例子。

    创建一个module.js的文件,内容是:

    var name;
    
    exports.setName = function(thyName){
        name = thyName;
    };
    
    exports.sayHello = function(){
        console.log('hello'+name);
    }

    在同一级目录下创建getmodule.js,内容是:

    var myModule = require('./module');
    
    myModule.setName('BYVoid');
    myModule.sayHello();

    运行getmodule.js,得到的结果是:hello BYVoid。

      你也许已经能理解exports和require对象的区别了吧。module.js通过exports对象把setName和sayHello作为模块的访问接口,在getmodule.js中通过require('./module')加载这个模块,然后就可以直接访问module.js中的exports对象的成员了。

    2.单次加载

      require不会重复加载模块,并且最终输出的结果是由后者决定的,就像同样的定义CSS属性,后者会覆盖前者一样。

      例如,我们在getmodule.js的基础上稍作修改:

    var hello1 = require('./module');
    hello1.setName('BYVoid 1');
    
    var hello2 = require('./module');
    hello2.setName('BYVoid 2');
    
    hello1.sayHello();

    运行的结果是: hello BYVoid 2。这是因为变量hello1和hello2指向的是同一个实例,因此hello1.setName的结果被hello2.setName覆盖。

    3.覆盖exports

      有时候我们只是把一个对象封装到模块中,例如:

    function Hello(){
        var name;
        this.setName = function (thyName) {
            name = thyName;
        };
        this.sayHello = function () {
            console.log('Hello' + name);
        };
    };
    
    exports.Hello = Hello;

      此时我们在其他文件中需要通过require('./singleobject').Hello来获取Hello对象,这略显冗余,因此可以用下面的方法稍微简化:

    function Hello() { 
        var name; 
        this.setName = function(thyName) { 
            name = thyName; 
        }; 
        this.sayHello = function() { 
            console.log('Hello ' + name); 
        }; 
    }; 
    module.exports = Hello;

    这样就可以直接获得这个对象了:

    var Hello = require('./hello');
    
    hello = new Hello();
    hello.setName('BYVoid');
    hello.sayHello();

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

      警告:不可以通过对 exports 直接赋值代替对 module.exports 赋值。exports 实际上只是一个和 module.exports 指向同一个对象的变量,它本身会在模块执行结束后释放,但 module 不会,因此只能通过指定module.exports 来改变访问接口。

  • 相关阅读:
    abstract关键字
    C#访问修饰符
    oracle客户端安装与配置
    Win10提示威胁服务已经停止,立即重启的解决方法
    什么是 Serverless 应用引擎?优势有哪些?
    Windows Server 2008 R2服务器系统安全设置参考指南
    Windows 2008 R2阿里云安全基线检查
    Windows Server 2008 R2 免费使用900天的方法
    Windows Server 2012 R2 英文版安装中文语言包教程
    七个穷人和富人不一样的地方
  • 原文地址:https://www.cnblogs.com/koto/p/5692433.html
Copyright © 2011-2022 走看看