简体   繁体   English

在javascript中,只要名称与局部变量相同,就可以访问全局变量?

[英]In javascript ,Access to global variable whenever its name is same with local variable?

var a="abc";
function(){
var a="efg";
console.log(a);//I need global variable value "abc" here
}
function();

I need the value "abc" in the console.我需要控制台中的值“abc”。 How can I get global variable value?如何获取全局变量值?

How can I get global variable value?如何获取全局变量值?

use window.a使用window.a

 var a = "abc"; function a1() { var a = "efg"; console.log(window.a); } a1()

In your specific example, since you used var at global scope, you can access it on the global object, which is accessible via the window global on browsers;在您的具体示例中,由于您在全局范围内使用了var ,因此您可以在全局对象上访问它,该对象可通过浏览器上的window global 访问; so window.a :所以window.a

 var a="abc"; function example(){ var a="efg"; console.log(window.a);//I need global variable value "abc" here } example();

However , if that global were created by using const , let , or class at global scope, eg:但是,如果该全局是通过在全局范围内使用constletclass创建的,例如:

let a = "abc";

...you would not be able to access it at all within that function, because even though globals created via const , let , or class are globals, they are not properties of the global object. ...您根本无法在该函数中访问它,因为即使通过constletclass创建的全局变量全局变量,它们也不是全局对象的属性。

How can I get global variable value a ?如何获得全局变量值a

By not naming your local variable a as well.也不要命名您的局部变量a

var a = "abc";
function example(){
    var b = "efg";
    console.log(a); // The global variable with the value "abc"
    console.log(b); // The local variable with the value "efg"
}
example();

It's local to your function anyway, so you can rename to it anything you want without impacting other functions.无论如何,它对您的函数来说是本地的,因此您可以将其重命名为任何您想要的名称,而不会影响其他函数。 Don't use names that you need to access global variables.不要使用访问全局变量所需的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM