Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG with reassigning #3699

Closed
celicoo opened this issue Nov 6, 2015 · 3 comments
Closed

BUG with reassigning #3699

celicoo opened this issue Nov 6, 2015 · 3 comments

Comments

@celicoo
Copy link

celicoo commented Nov 6, 2015

~ DELETED ~

@mscdex
Copy link
Contributor

mscdex commented Nov 6, 2015

This isn't a bug. module.exports is only assigned once and it is cached by require(). You cannot magically change function references globally and directly like you are expecting.

However, one solution to this could be to return an object that holds a reference to the current sum() and reference that property in your main script instead. For example:

// sum.js
function sum(a) {
  console.log('test');
  exports.sum = function(b) {
    console.log(a + b);
  };
}

exports.sum = sum;
// main.js
var obj = require('./sum');

obj.sum(10);
obj.sum(15);
// outputs:
// test
// 25

@mscdex mscdex closed this as completed Nov 6, 2015
@celicoo
Copy link
Author

celicoo commented Nov 6, 2015

What if i want call sum one time from two other files? @mscdex

@mscdex
Copy link
Contributor

mscdex commented Nov 6, 2015

If you need separate instances, then return new instances of sum() instead of the same function/instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants