是否有任何方法可以访问外部范围's变量

Is there any way to access an outer scope's variable once the present scope has defined one of the same name?

本文关键字:范围 变量 外部 访问 任何 方法 是否      更新时间:2023-10-08

这似乎不是:

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就没有办法获得ov

当然,如果您对变量使用不同的名称,那么问题就会消失。:-)


如果不是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

不过,这在严格模式下不起作用,因为this将是i中的undefined

在浏览器上,全局对象有一个属性window,它用来引用自己,所以您不必像上面的那样依赖this

// Browsers only
var v = 1;
function i() {
    var v = 2;
    console.log("v == " + v);
    console.log("window.v == " + window.v);
}
i();

这可以在严格模式或宽松模式下工作,但仅适用于浏览器。

但全球范围是一个特例。对于你引用的代码,不,没有办法到达那里。