Skip to content

Instantly share code, notes, and snippets.

@humbletim
Forked from anonymous/car.js
Created February 7, 2017 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humbletim/215dca361c2758539c786c2682fb38a2 to your computer and use it in GitHub Desktop.
Save humbletim/215dca361c2758539c786c2682fb38a2 to your computer and use it in GitHub Desktop.
Node circular dependencies example
var gas = require('./gas');
var speed = 0;
exports.drive = function () {
gas.burn();
};
exports.accelerate = function () {
speed += 10;
console.log('Car is going: ' + speed);
};
var car = require('./car');
console.log('Car module (incomplete):', car);
// If I try to invoke "car.accelerate()" here, that method is not yet defined and it will error!
// This is what you want to avoid - directly using another dependency in the high-level code that
// runs while this module itself is being defined.
//
// Uncomment this line and see yourself:
//car.accelerate();
exports.burn = function () {
// But invoking "car.accelerate()" in here is fine. By the time
// the code inside this function is running, car.accelerate()
// will be defined.
console.log('Car module (complete):', car);
car.accelerate();
};
var car = require('./car');
car.drive();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment