似乎不是:
function o(){
var v = 1;
function i(){
var v = 2;
// any way at all, now, to access the 1 value?
}
}
但是有吗?
最佳答案
不行,i
中的 v
符号完全遮盖了 o
中的 v
,没有别的办法得到它。使用该代码,i
无法访问 o
的 v
。
当然,如果您对变量使用不同的名称,这个问题就会消失。 :-)
如果不是 o
而不是 global 范围内的代码,您可以将 v
作为全局对象的属性进行访问,因为当您全局声明一个变量,它就成为全局对象的一个属性。例如,这将在松散模式下工作:
var v = 1;
function i() {
var v = 2;
console.log("v == " + v);
console.log("this.v == " + this.v);
}
i(); // Calling it like this makes `this` within the call the global object
哪个会显示
v == 2; this.v == 1
That wouldn't work in strict mode, though, because this
would be undefined
within i
.
On browsers, the global object has a property, window
, it uses to refer to itself, so you wouldn't have to rely on this
as with the above:
// Browsers only
var v = 1;
function i() {
var v = 2;
console.log("v == " + v);
console.log("window.v == " + window.v);
}
i();
这在严格模式或松散模式下都有效,但仅在浏览器中有效。
但是全局范围是一个特例。对于您引用的代码,不,没有办法到达那里。
关于javascript - 一旦当前范围定义了一个相同名称的变量,是否有任何方法可以访问外部范围的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20194836/