简体   繁体   English

用冲突的局部变量重新定义全局变量

[英]Re-defining global variable with conflicting local variable

So I was trying to get a handle on JavaScript's scope and looking up lots of info about it. 因此,我试图了解JavaScript的范围,并查找有关它的很多信息。 I saw a lot of questions about people accidentally making local variables that conflicted with global ones. 我看到了很多有关人们意外地创建与全局变量冲突的局部变量的问题。

But I was wondering if there was a way to change global variables despite a conflicting local variable. 但是我想知道,尽管局部变量冲突,是否有办法改变全局变量。 Like: 喜欢:

    var globalVariable = 6;

    var func1 = function() {
       this.func2 = function() {
          var globalVariable = 99;   
                   = 7;
       }
    };
    print(globalVariable);

Is there a way to change the global variable value despite that conflicting local variable name? 尽管存在局部变量名称冲突,是否有办法更改全局变量值?

When I tried this.globalVariable = 7 to print 7 as the output, it did not work. 当我尝试this.globalVariable = 7this.globalVariable = 7打印为输出时,它不起作用。 Can anyone make clear why the this. 任何人都可以弄清楚为什么this. access did not work or if there is even a way to change the global variable if there does happen to be a local of conflicting name? 访问不起作用,或者如果确实存在名称冲突的本地变量,甚至还有办法更改全局变量?

Obviously it would not make sense to write code this way, but I thought I understood that the this. 显然,用这种方式编写代码是没有意义的,但是我认为我理解了this. keyword always specified the global variable/object? 关键字始终指定全局变量/对象?

You could use window['globalVariable'] = 7; 您可以使用window ['globalVariable'] = 7;

It's not a good solution though. 但是,这不是一个好的解决方案。 There really are none. 真的没有。

The "this" variable refers to the scope the current function has, usually, unless it was bound to something else or called/applied (.call/.apply). “此”变量是指当前函数通常具有的作用域,除非将其绑定到其他函数或调用/应用(.call / .apply)。 I'd suggest Googling function scope because it can get quite confusing. 我建议使用Googling函数范围,因为它可能会引起混乱。

I'm on Skype if you have any more questions (thetenfold). 如果您还有其他问题,我在Skype上。

"I thought I understood that the this. keyword always specified the global variable/object?" “我以为我知道this.关键字总是指定全局变量/对象?”

No. The value of this depends on how a function is called and whether the function is in strict mode . 号的值, this取决于函数是如何被调用以及是否功能在严格模式

In the browser global variables are properties of the window object, so use: 在浏览器中,全局变量是window对象的属性,因此请使用:

window.globalVariable = 7;

Sometimes this is equal to window , but often it is not. 有时, this等于window ,但通常不是。 (I don't mean that to sound like this just gets set randomly; there is a specific set of rules that apply.) (我的意思并不是说听起来像this刚刚被随机设置;还有一个规则组特定的适用。)

Note that if you find yourself needing to distinguish between global variables and local variables like this you might well be using too many global variables. 请注意,如果您发现需要像这样区分全局变量和局部变量,则可能使用了太多的全局变量。

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

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