更改范围外的变量? [英] Changing a Variable Out of Scope?

查看:38
本文介绍了更改范围外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在超出范围时更改变量?我知道一般来说,你不能,但我想知道是否有任何技巧或覆盖.例如,有什么方法可以使以下工作:

Is there any way to change a variable while out of scope? I know in general, you cannot, but I'm wondering if there are any tricks or overrides. For example, is there any way to make the following work:

function blah(){
 var a = 1
}
a = 2;
alert(blah());

编辑(为了澄清):

假设场景是修改在 setInterval 函数中使用的变量,该函数也在范围之外且在不可编辑的先前 javascript 文件中.这是一个非常古怪的场景,但这是我打算询问的.

The hypothetical scenario would be modifying a variable that is used in a setInterval function which is also out of scope and in an un-editable previous javascript file. It's a pretty wacky scenario, but it's the one I intend to ask about.

推荐答案

没有.没有技巧或覆盖.您必须计划让两个地方都能在同一范围内看到变量.

No. No tricks or overrides. You have to plan to have both places be able to see the variable in the same scope.

我能想到的关于作用域的唯一技巧是在浏览器中使用 window 来访问全局对象.这可以帮助您找到一个隐藏"变量——一个在作用域内但其名称已被局部变量(或作用域链中更接近的其他变量)取代的变量.

The only trick I can think of regarding scope is using window in a browser to get to the global object. This can help you get to a "hidden" variable--one that's in scope but whose name has been overtaken by a local variable (or other variable closer in the scope chain).

闭包和类可以为您提供一些其他的作用域技巧,但都不能让您完全覆盖作用域规则.

Closures and classes can afford you some other tricks with scope, but none that allow you to override the scoping rules entirely.

这篇关于更改范围外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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