简体   繁体   English

选择全局范围而不是本地范围

[英]Picking global scope over local

I wonder, If is it any way in Javascript to tell compiler from which scope variable you wanna use.我想知道,在 Javascript 中是否有任何方式告诉编译器您要使用哪个范围变量。

Like in python appending keyword global and compiler knows that you're using global one.就像在 python 中附加关键字global ,编译器知道您正在使用 global 一个。

Is it any way to do same in Javascript, beside using a different name?除了使用不同的名称之外,还有什么方法可以在 Javascript 中做同样的事情吗?

(In the sample below I'm trying to reach out for global "red", but it's been shadowing with argument "green".) (在下面的示例中,我试图接触全局“红色”,但它一直被参数“绿色”遮蔽。)

 const color = "red" const printColor = (color) => console.log(color) printColor("green")

Attach the global var directly to the window object:将全局变量直接附加到 window 对象上:

 window.color = "red" const printColor = (color) => console.log(color, window.color) printColor("green")

Update更新

Alternatively, you could create a "global" object and keep all your global vars in it:或者,您可以创建一个“全局”对象并将所有全局变量保存在其中:

 const global = { color: "red" } const printColor = (color) => console.log(color, global.color) printColor("green")

I like @symlink 's answer, but just as an additional bit of information.我喜欢 @symlink 的答案,但只是作为额外的信息。

A way to do this would be to bind the context of the appropriate this to the function.一种方法是将适当的thiscontext绑定到函数。

For instance, because var will hoist variables ( outside of strict mode ) to window , you could potentially do something like the following:例如,因为var会将变量(严格模式之外)提升到window ,您可能会执行以下操作:

 var color = "blue"; const printColor = function() { console.log(this.color) } printColor.bind( window )() printColor.bind({ color: "green" })()

We could also shorthand this to simply accept the scope as the argument.我们也可以将其简写为简单地接受scope作为参数。

 var color = "blue"; const printColor = scope => console.log(scope.color) printColor(window); printColor({color: "green"})

The comparison with Python should be done in a fair way.与 Python 的比较应该以一种公平的方式进行。

When in Python you have:在 Python 中,您有:

x = 1 # global
def test(x):
    print(x)

... you cannot insert the global keyword to let that print(x) act on the global x , as you already defined that name as a local name (a parameter). ...您不能插入global关键字来让print(x)作用于全局x ,因为您已经将该名称定义为本地名称(参数)。

To continue for a moment in the Python world.继续在 Python 世界中停留片刻。 This will act on the global variable:这将作用于全局变量:

x = 1
def test():
    print(x) # global

...but as soon as you have an assignment, the variable will be considered to be local: ...但是一旦你有一个赋值,变量就会被认为是本地的:

x = 1
def test():
    x = 2 # local
    print(x)

To override this behaviour, you use global :要覆盖此行为,请使用global

x = 1
def test():
    global x
    x = 2 # global
    print(x) 

Now, back to JavaScript.现在,回到 JavaScript。 Here you can play with the word var .在这里,您可以使用var一词。

To use the variable within the function, you just omit defining it with let , const or var in there:要在函数中使用变量,只需在其中省略使用letconstvar定义它:

var x = 1;

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

To use the variable as local variable, then do use var , let or const :要将变量用作局部变量,使用varletconst

var x = 1;

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

So it is not that different.所以它并没有那么不同。 When in Python you use the global keyword, you don't use var , let or const in JavaScript, and where you omit Python's global , you do use var , let or const in JavaScript.当在Python中使用global关键字,您不使用varletconst在JavaScript中,并在您省略Python的global使用varletconst在JavaScript中。

globals() versus globalThis globals()globalThis

Python has globals() with which you can reference a global variable when you also have a local variable with the same name: Python 有globals() ,当你还有一个同名的局部变量时,你可以用它引用一个全局变量:

x = 1

def test(x = 2):
    globals()['x'] = 3 # modifies the global variable

In JavaScript you would be able to do this via the global object, which is window in a browser context.在 JavaScript 中,您可以通过全局对象(浏览器上下文中的window来执行此操作。 See also the newer globalThis .另见较新的globalThis So in a browser context you can do this (but it needs var ):所以在浏览器上下文中你可以这样做(但它需要var ):

var x = 1;

function test(x = 2) {
    window.x = 3 // modifies the global variable
}

It would be better practice though, to just define your global variable as part of an object:不过,最好将全局变量定义为对象的一部分:

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