2

For the sake of an example, here's something contrived:

var util = require('util');
var Me = require('./me.js');

console.log(util.inspect(Me.prototype.something.toString())); // #1      

Me.prototype.name = function() {
  console.log('different');
};

console.log(util.inspect(Me.prototype.something.toString())); // #2

// re-init prototype
var Me = require('./me.js');
console.log(util.inspect(Me.prototype.something.toString())); // #3

Output:

'function () {\n    console.log(\'original\');\n}'
'function () {\n    console.log(\'different\');\n}'
'function () {\n    console.log(\'different\');\n}'

Why doesn't the require call re-init Me class prototype?

wulfgarpro
  • 6,666
  • 12
  • 69
  • 110

2 Answers2

1

require caches the code, so when called repeatidly it doesn't reload it again. Since the Me object is still in memory it doesn't get reloaded when you require it again.

If you want to do this you have to delete Me from the module cache.

See this answer How to remove module after "require" in node.js?

Community
  • 1
  • 1
akc42
  • 4,893
  • 5
  • 41
  • 60
1

From Nodejs Documentation, LINK

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.

Oxi
  • 2,918
  • 17
  • 28