简体   繁体   中英

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; . Normally, this will make myVar be equal to 2 inside the function. 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 )?

A quick review of global variables first:

Global variables declared using var or let behave differently. 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 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. 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. 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,

  1. 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. 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.

  2. Executing window.myVar = 2 within a function will only update the value of a global myVar variable if it was declared using var . It may create a window property but will not update the value of a global let variable.

So the value of myVar shown in an alert after the function has been called depends on

  • whether the global declaration has been shadowed by re-declaring the variable within function scope (either locally within a function or in an outer function),
  • whether myVar was referenced using an unadorned identifier or as a named window property, in conjunction with
  • whether myVar was originally declared using var or let .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM