![](/img/trans.png)
[英]Any way to access local scope variable in outer scope in Javascript?
[英]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?
}
}
但是有嗎?
不,在i
, v
符號完全遮蔽了o
的v
,並且沒有其他方法可以實現它。 有了這個代碼, i
無法獲得o
的v
。
當然,如果您為變量使用了不同的名稱,那么問題就會消失。 :-)
如果不是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
在嚴格模式下不起作用,因為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();
這適用於嚴格或松散模式,但僅適用於瀏覽器。
但全球范圍是一個特例。 對於你引用的代碼,不,沒有辦法到達那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.