模块

作者: 欣_m | 来源:发表于2019-08-27 21:21 被阅读0次

    一个Node.js文件就是一个模块

    Node.js提供 exports 和 require 两个对象,其中 exports 是模块公开

    的接口,require 用于从外部获取一个模块的接口,即所获取模块的

    exports 对象。


    创建模块1

    1.首先创建hello.js文件

    exports.show = function(){---------通过exports对象把show作为模块访问接口

     console.log('hi!!!!!!')

    }

    2.创建main.js

    var hello = require ('./hello');-------引入当前目录下的hello.js文件

    hello.show();--------访问hello.js中的成员函数


    创建模块2(将对象封装)

    1.创建moduleEmployee.js

    function Employee() {

       var name = 'Lily' -----这里不需要写 this

        var sex = 'female'

        this.display = function () {

    console.log("我是:"+name+",性别:"+sex) -----这里不需要写this.name

    }

    }

    module.exports=Employee;       ----代替 exports.class=function(){}

    如果另外写了this.setname=function(){

    this.name=name;------这里要写this,consol.log也统一写this

    }

    2.创建exports.js

    var Employee = require('./moduleEmployee')-------引入文件

    var Emp = new Employee();------获取对象

    Emp.display();------获取方法

    相关文章

      网友评论

          本文标题:模块

          本文链接:https://www.haomeiwen.com/subject/ejvyectx.html