How to access global variable from a function when

2019-09-21 05:19发布

问题:

This question already has an answer here:

  • Access overridden global variable inside a function 2 answers

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 with the passed value
}

回答1:

If you are really talking about a global variable this can be done this way:

function func(name) {
  window.name=name;
}

in a browser or

function func(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.



回答2:

Change the name of the parameter to something else. No other way, because it will always see the innermost name.



回答3:

var name = 'Name outer';

function func(name) {
  console.log(name);
  console.log(window.name);
}

func ('Name inner');

However, this would be bad practice and you should avoid having this situations.