[英]will declaring window.variable in a function make the value global?
Okay, so let's say that I have a global variable myVar
, and in a function myFunction()
, I write myVar = 2;
好吧,那么让我说我有一个全局变量
myVar
,并且在一个函数myFunction()
,我写了myVar = 2;
. 。 Normally, this will make
myVar
be equal to 2
inside the function. 通常,这将使
myVar
在函数内等于2
。 My question is, will declaring window.myVar = 2
in the function make myVar
equal to 2
globally (so, alert(myVar)
outside the function returns 2
)? 我的问题是,在函数中声明
window.myVar = 2
将使myVar
等于2
全局 (因此,函数外的alert(myVar)
返回2
)?
A quick review of global variables first: 首先快速回顾一下全局变量:
Global variables declared using var
or let
behave differently. 使用
var
或let
声明的全局变量的行为方式不同。 A global variable defined using var
create a non-configurable property of the global object, using the name of the variable, which can't be deleted. 使用
var
定义的全局变量使用无法删除的变量名称创建全局对象的不可配置属性。
var x = "var x"; console.log("window.x: " + window.x); console.log( JSON.stringify(Object.getOwnPropertyDescriptor(window, "x")))
But a global variable declared with let
does not become a property of the global object. 但是使用
let
声明的全局变量不会成为全局对象的属性。 If you have a window
property (in a browser) and a let
variable of the same name, you have to qualify the window property with window.
如果你有一个
window
属性(在浏览器中)和一个同名的let
变量,你必须用window.
限定window属性window.
to access it: 访问它:
let y = "let y"; window.y = "window.y"; console.log("y = " + y + "( using the identifier only)"); console.log("window.y = " + window.y);
Now getting back to the question, 现在回到这个问题,
If you declare myVar
in global scope and reference it within a function, you will access the global variable, provided you have not re-declared the variable within the function or any outer nested function. 如果在全局范围内声明
myVar
并在函数内引用它,则将访问全局变量, 前提是您尚未在函数或任何外部嵌套函数中重新声明该变量。 Without redeclaraion, such access works for both reading and writing and executing myVar = 2
within the function will update the value of the global variable. 如果没有重新编译,这种访问既可用于读取也可用于写入,并且在函数内执行
myVar = 2
将更新全局变量的值。
Executing window.myVar = 2
within a function will only update the value of a global myVar
variable if it was declared using var
. 在函数内执行
window.myVar = 2
只会更新全局myVar
变量的值(如果使用var
声明它)。 It may create a window property but will not update the value of a global let
variable. 它可能会创建一个窗口属性,但不会更新全局
let
变量的值。
So the value of myVar
shown in an alert after the function has been called depends on 因此调用函数后在警报中显示的
myVar
值取决于
myVar
was referenced using an unadorned identifier or as a named window property, in conjunction with myVar
,结合使用 myVar
was originally declared using var
or let
. myVar
最初是使用var
还是let
声明的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.