煦煦

web前端

煦煦的个人站~


node模块封装方法

  • Require:用于获取模块的方法
  • Exports:在被封装的模块中,定义外部接口

方法一: 模块中只有一个函数

hello.js

exports.world = function() {  
  console.log('Hello World');  
}

main.js中调用:

var hello = require('./hello');//获取hello.js模块  
hello.world();//调用hello.js中的word方法  

方法二:传参

hello.js

module.exports=function(name){
  console.log('Hello '+name);  
}

main.js中调用:

require('./hello')(name);

方法三:可声明多个函数

hello.js

module.exports={
    helloWorld:function(){
        console.log('hello world!');
    },
    helloName:function(name){
        console.log('hello '+name);
    }
}

main.js中调用:

var hello=require(./hello);
hello.helloWorld();
hello.helloName(name);

方法四:直接封装一个对象

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 = new Hello();//实例化   
hello.setName('BYVoid');   
hello.sayHello();