当名称与JavaScript中的参数名称相同时,如何从函数访问全局变量? [英] How to access global variable from a function when the name is same as argument name in JavaScript?

查看:98
本文介绍了当名称与JavaScript中的参数名称相同时,如何从函数访问全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当名称与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 with the passed value
}

推荐答案

如果您真的在谈论全局变量,可以这样:

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

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

在浏览器中或

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

在node.js中,但是如果您在函数中声明了name,那么afaik将无法做到这一点.

in node.js but if you declared name within a function there is afaik no way to do that.

但是,您应该尽可能避免使用gobal变量,因为它们已被所有使用的代码(包括库)共享,并且您不知道它是否会对名称产生任何副作用.

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.

这篇关于当名称与JavaScript中的参数名称相同时,如何从函数访问全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆