Reputation: 19651
How to access global variable from a function when the name is same as argument name in Node.js ?
var name = null;
function func(name) {
// How to set the global variable with the passed value
}
Upvotes: 3
Views: 4309
Reputation: 707198
Assuming you're talking about a node.js module, your first name
variable is not actually global - it's just in a higher scope in the module (defined at the module level). As such, there is no way to access it from within a function that has an argument with the same name in Javascript.
You will have to change the name of one or the other of the two conflicting names in order to be able to access both.
var name = null;
// change the name of the argument
function func(aname) {
name = aname;
}
func("Bob");
console.log(name); // "Bob"
If it was actually a global in node.js, then you could access it with the global
prefix as in:
global.name = "Bob";
function func(name) {
global.name = name;
}
function("Alice);
console.log(global.name); // "Alice"
FYI, in general I'd stay away from global variables named name
. If this were browser code, there's already a window.name
that would conflict.
Here's a little primer on actual using global variables in node.js (which is generally not recommended). Sharing exported properties/variables/methods is what is recommended in node.js.
Upvotes: 4