2017-08-06 59 views
-3

我想用「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"); 

訪問變量還是我必須給他們不同的重命名?

+2

您可以用'window.frutch'訪問全局。但不是具有相同名稱的最佳做法 – sheplu

+0

您是否在嚴格模式下運行此代碼?否則,應該工作。 – 4castle

+2

我知道它可能並不是宇宙中最好的問題,但我敢肯定,沒有人會從downvoting中學到任何東西,而沒有解釋爲什麼...... –

回答

1

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');

另見:https://www.npmjs.com/package/system.global

1

如果你的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");

1

如果是全球您正在瀏覽器中運行:

您可以使用window.frucht作爲全局變量是window對象的屬性。

不重複使用相同的變量名將是一個更好的主意。它避免了對全局變量的依賴以及對重用名稱的混淆。

1

一般來說,在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訪問變量)

希望有所幫助。