How to access global variable from a function when the name is same as argument name in JavaScript? [duplicate]

夙愿已清 提交于 2019-12-13 09:17:25

问题


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.



来源:https://stackoverflow.com/questions/35976005/how-to-access-global-variable-from-a-function-when-the-name-is-same-as-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!