This code outputs the following:
---------- local
one
---------- ref
one
---------- before re-require
---------- local
one
---------- ref
two
---------- after required
---------- local
one
two
---------- ref
two
two
'use strict'; | |
var mod = require('./module'); | |
var fn = mod.fn; | |
log('local'); | |
// calling the local variable - this is a copy of the reference to `one` | |
fn(); | |
log('ref'); | |
// calling the *reference* to `one` | |
mod.fn(); | |
setTimeout(function () { | |
log('before re-require'); | |
log('local'); | |
fn(); | |
log('ref'); | |
mod.fn(); | |
var mod2 = require('./module'); | |
var fn2 = mod.fn; | |
log('after required'); | |
log('local'); | |
fn(); | |
fn2(); | |
log('ref'); | |
mod.fn(); | |
mod2.fn(); | |
}, 2000); | |
function log(s) { | |
console.log('\n---------- ' + s); | |
} |
'use strict'; | |
function one() { | |
console.log('one'); | |
} | |
function two() { | |
console.log('two'); | |
} | |
module.exports = { | |
fn: one | |
}; | |
setTimeout(function () { | |
module.exports.fn = two; | |
}, 1000); |
Got it ! Tricky though, and must say its not that obvious,
If I understand it correctly, if the first call to mod.fn(); [line-12] takes more than 1 seconds, it will output two instead of one ! ?