Skip to content

Instantly share code, notes, and snippets.

@remy
Last active August 29, 2015 14:01
Show Gist options
  • Save remy/621c2fc452f3b89a6dc1 to your computer and use it in GitHub Desktop.
Save remy/621c2fc452f3b89a6dc1 to your computer and use it in GitHub Desktop.
I understand why and how this works, but it always catches me out. I wonder how obvious it is to others? Feel free to comment below.

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);
@supratims
Copy link

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 ! ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment