![](/img/trans.png)
[英]Scope: passing a local variable over to a global variable in JavaScript
[英]Picking global scope over local
我想知道,在 Javascript 中是否有任何方式告訴編譯器您要使用哪個范圍變量。
就像在 python 中附加關鍵字global
,編譯器知道您正在使用 global 一個。
除了使用不同的名稱之外,還有什么方法可以在 Javascript 中做同樣的事情嗎?
(在下面的示例中,我試圖接觸全局“紅色”,但它一直被參數“綠色”遮蔽。)
const color = "red" const printColor = (color) => console.log(color) printColor("green")
將全局變量直接附加到 window 對象上:
window.color = "red" const printColor = (color) => console.log(color, window.color) printColor("green")
或者,您可以創建一個“全局”對象並將所有全局變量保存在其中:
const global = { color: "red" } const printColor = (color) => console.log(color, global.color) printColor("green")
我喜歡 @symlink 的答案,但只是作為額外的信息。
一種方法是將適當的this
的context
綁定到函數。
例如,因為var
會將變量(嚴格模式之外)提升到window
,您可能會執行以下操作:
var color = "blue"; const printColor = function() { console.log(this.color) } printColor.bind( window )() printColor.bind({ color: "green" })()
我們也可以將其簡寫為簡單地接受scope
作為參數。
var color = "blue"; const printColor = scope => console.log(scope.color) printColor(window); printColor({color: "green"})
與 Python 的比較應該以一種公平的方式進行。
在 Python 中,您有:
x = 1 # global
def test(x):
print(x)
...您不能插入global
關鍵字來讓print(x)
作用於全局x
,因為您已經將該名稱定義為本地名稱(參數)。
繼續在 Python 世界中停留片刻。 這將作用於全局變量:
x = 1
def test():
print(x) # global
...但是一旦你有一個賦值,變量就會被認為是本地的:
x = 1
def test():
x = 2 # local
print(x)
要覆蓋此行為,請使用global
:
x = 1
def test():
global x
x = 2 # global
print(x)
現在,回到 JavaScript。 在這里,您可以使用var
一詞。
要在函數中使用變量,只需在其中省略使用let
、 const
或var
定義它:
var x = 1;
function test() {
console.log(x); // global
}
要將變量用作局部變量,請使用var
、 let
或const
:
var x = 1;
function test() {
var x = 2; // local
console.log(x);
}
所以它並沒有那么不同。 當在Python中使用global
關鍵字,您不使用var
, let
或const
在JavaScript中,並在您省略Python的global
,您使用var
, let
或const
在JavaScript中。
globals()
與globalThis
Python 有globals()
,當你還有一個同名的局部變量時,你可以用它來引用一個全局變量:
x = 1
def test(x = 2):
globals()['x'] = 3 # modifies the global variable
在 JavaScript 中,您可以通過全局對象(瀏覽器上下文中的window
來執行此操作。 另見較新的globalThis
。 所以在瀏覽器上下文中你可以這樣做(但它需要var
):
var x = 1;
function test(x = 2) {
window.x = 3 // modifies the global variable
}
不過,最好將全局變量定義為對象的一部分:
var myglobals = { x: 1 };
function test(x = 2) {
myglobals.x = 3 // mutates myglobals
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.