How To Access Global Variable From A Function When The Name Is Same As Argument Name In Javascript?
How to access global variable from a function when the name is same as argument name in JavaScript ? var name = null; function func(name) { // How to set the global variable wit
Solution 1:
Change the name of the parameter to something else. No other way, because it will always see the innermost name
.
Solution 2:
var name = 'Name outer';
functionfunc(name) {
console.log(name);
console.log(window.name);
}
func ('Name inner');
However, this would be bad practice and you should avoid having this situations.
Solution 3:
If you are really talking about a global variable this can be done this way:
functionfunc(name) {
window.name=name;
}
in a browser or
functionfunc(name) {
global.name=name;
}
in node.js but if you declared name
within a function there is afaik no way to do that.
However, you should avoid gobal variables if possible because they are shared by all used code including libraries and you can't know if this has any side effects in case of a name colision.
Post a Comment for "How To Access Global Variable From A Function When The Name Is Same As Argument Name In Javascript?"