簡體   English   中英

一旦當前范圍定義了同一個名稱,有沒有辦法訪問外部范圍的變量?

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

它似乎不是:

function o(){
  var v = 1;
  function i(){
    var v = 2;
    // any way at all, now, to access the 1 value?
  }
}

但是有嗎?

不,在iv符號完全遮蔽了ov ,並且沒有其他方法可以實現它。 有了這個代碼, i無法獲得ov

當然,如果您為變量使用了不同的名稱,那么問題就會消失。 :-)


如果不是o而是在全局范圍內使用代碼,則可以將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在嚴格模式下不起作用,因為thisiundefined

在瀏覽器上,全局對象有一個屬性, window ,它用於引用自身,所以你不必像上面那樣依賴this

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

這適用於嚴格或松散模式,但僅適用於瀏覽器。

但全球范圍是一個特例。 對於你引用的代碼,不,沒有辦法到達那里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM