我想用「apfala」如何訪問全局變量而不是參數值?
var frucht="apfala";
function getFrucht(frucht){
console.log(frucht);
console.log(this.frucht) // I want here the apfala one, I thought .this would work
}
getFrucht("apfel");
訪問變量還是我必須給他們不同的重命名?
我想用「apfala」如何訪問全局變量而不是參數值?
var frucht="apfala";
function getFrucht(frucht){
console.log(frucht);
console.log(this.frucht) // I want here the apfala one, I thought .this would work
}
getFrucht("apfel");
訪問變量還是我必須給他們不同的重命名?
http://eslint.org/docs/rules/no-shadow
陰影是過程,通過該局部變量共享相同的名稱 在其含有範圍的變量。例如:
var a = 3; function b() { var a = 10; }
在這種情況下,變量b的內部()被遮蔽的變量在全球範圍 。這會在讀取代碼 時造成混淆,並且無法訪問全局變量。
你的代碼表明你需要重新考慮你想要做的任何事情。由於不清楚你想要做什麼的真實性質,如果你有一個而不僅僅是好奇心,很難爲你的問題提供一個替代解決方案(除了不要影響或使用全局變量)嗎?
請不要這樣做,但這應該適用於所有環境。
'use strict';
var getGlobal = Function('return this');
getGlobal().frucht = 'apfala';
function getFrucht(frucht) {
console.log(frucht);
console.log(getGlobal().frucht); // I want here the apfala one, I thought .this would work
}
getFrucht('apfe');
如果你的JavaScript在瀏覽器中運行,您可以使用window
全局變量,以訪問變量frucht
,在全球範圍內定義:
var frucht="apfala";
function getFrucht(frucht){
console.log(frucht);
console.log(window.frucht) // I want here the apfala one, I thought .this would work
}
getFrucht("apfel");
如果是全球和您正在瀏覽器中運行:
您可以使用window.frucht
作爲全局變量是window
對象的屬性。
不重複使用相同的變量名將是一個更好的主意。它避免了對全局變量的依賴以及對重用名稱的混淆。
一般來說,在JavaScript中,如果你想父母範圍傳遞給孩子一個,你需要在父分配this
一個變量,並且訪問子內部的變量:
var frucht="apfala";
var parent = this;
function getFrucht(frucht){
console.log(frucht);
console.log(parent.frucht);
}
getFrucht("apfel");
而且,在其他的答案說,如果你在瀏覽器中運行,只需使用window
對象連接和訪問全局變量(window.frucht="apfala"
,然後使用window.frucht
訪問變量)
希望有所幫助。
您可以用'window.frutch'訪問全局。但不是具有相同名稱的最佳做法 – sheplu
您是否在嚴格模式下運行此代碼?否則,應該工作。 – 4castle
我知道它可能並不是宇宙中最好的問題,但我敢肯定,沒有人會從downvoting中學到任何東西,而沒有解釋爲什麼...... –