初识Node.js模块化

初识Node.js模块化

我先来谈一下,我对Node模块化的理解,我觉得他很像Java中的封装,把很多变量和方法封装在一起。

先来看一下,如果有两个js(mian.js和 b.js),其中main.js为主程序,加载b.js。这时我们在b.js中可以“封装”一些参数和方法。


模块化一个参数或方法

main.js

var Bexports = require('./b');

console.log(Bexports);

b.js(模块化一个参数)

var hello = 'hello node';

module.exports = hello;

运行 main.js 结果

main.js

var Bexports = require('./b');

console.log(Bexports(1,2));

运行 main.js 结果

b.js(模块化一个方法)

module.exports = function(x,y){
    return x+y;
};

function add(x, y) {
    return x+y;
}
module.exports=add;

当封装多个参数和方法时,可使用如下方法

main.js

var Bexports = require('./b');

console.log(Bexports.str);
console.log(Bexports.hello);
console.log(Bexports.add(1,3));

b.js

module.exports.str='This is str';
module.exports.hello='hello';
module.exports.add=function (x, y) {
    return x+y;
};


或
function add (x, y) {
    return x+y;
};
module.exports.add=add;

或者像Json一样,这样定义

module.exports = {
    str:'This is str',
    hello:'hello',
    add:function (x, y) {
        return x+y;
    }
}

运行 main.js 结果:

猜你喜欢

转载自blog.csdn.net/LitongZero/article/details/81395905