d
k
p
l
u
s

模块初始化

假设有模块counter.js:

var i = 0;

function count() {
    return ++i;
}

exports.count = count;

主模块main.js:

var counter1 = require('./util/counter');
var    counter2 = require('./util/counter');

console.log(counter1.count());
console.log(counter2.count());
console.log(counter2.count());

/**
 * 运行结果:
  1
  2
  3
 * /

由此说明,虽然模块被多次引入,但只会初始化一次。

posted @ 2018-03-02 14:12  dkplus  阅读(229)  评论(0编辑  收藏  举报