簡體   English   中英

選擇全局范圍而不是本地范圍

[英]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 的答案,但只是作為額外的信息。

一種方法是將適當的thiscontext綁定到函數。

例如,因為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一詞。

要在函數中使用變量,只需在其中省略使用letconstvar定義它:

var x = 1;

function test() {
    console.log(x); // global
}

要將變量用作局部變量,使用varletconst

var x = 1;

function test() {
    var x = 2; // local
    console.log(x);
}

所以它並沒有那么不同。 當在Python中使用global關鍵字,您不使用varletconst在JavaScript中,並在您省略Python的global使用varletconst在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.

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