初识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 结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值