I'm trying to pass a variable to a IIFE in another file (a module required ) but it is ignored.
index.js
var modulo = require('./modulo');
modulo.foo = "newFoo";
console.log(modulo.foo);
console.log(modulo.myFunction.innerFunction());
modulo.js
var foo = "oldFoo";
var myFunction = (function(innerFoo) {
return {
innerFunction: function () {
return "Returning innerFunction with " + innerFoo;
}
};
})(foo);
module.exports.foo = foo;
module.exports.myFunction = myFunction;
Now when I execute node index.js
the result is:
newFoo
Returning innerFunction with oldFoo
How can I pass the newFoo variable so modulo.js can use it internally?
(Actually, I want to pass a socket so my module.js can use it for communication with the server)
Thank you very much in advance!!
modulo.js
module.exports.foo = "";
var myFunction = (function() {
return {
innerFunction: function () {
var innerFoo = module.exports.foo;
return "Returning innerFunction with " + innerFoo;
}
};
})();
module.exports.myFunction = myFunction;
Your IIFE does not read from module.foo
, which you are overwriting, but from the actual foo
variable in modulo.js
. Javascript is Pass-by-value with primitive values ;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.