简体   繁体   中英

Why does the global variable value show up as undefined?

 const mode = "portfolio"; document.addEventListener('keydown',(event) => { console.log(event.key); if(event.key === 'ArrowUp' || event.key === 'ArrowDown'){ modeToggle(); } }) const modeToggle = function() { console.log(`mode toggle called, current mode is ${this.mode}`); if(this.mode == "portfolio") { this.mode ="blog"; } else if(this.mode == "blog"){ this.mode ="portfolio"; } console.log(this.mode); }

this.mode comes up as 'undefined' in the console log.

Can you please help me understand why the this.mode variable's value is undefined? Thanks:)

PS - First question on stackflow:P

Because this is in an event handler, it is referencing the object that triggered the event, in this case that would normally be the document . But, because you used an Arrow Function as the callback, this is not actually modified from whatever it was referencing prior to the invocation, which in this case actually was window , however because you used const , your variable got block level scope and didn't bind as a window property as stated in the documentation :

This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the window object, unlike var variables.

To access a Global, don't use this or, if you wanted to use this with window , declare the variable with var so you don't get block level scope.

Also, if you want to be able to modify the variable, don't declare it with const (constant).

 // If you want to be able to modify a variable value, // you can't have it declared as a constant. And, by // declaring with const or let, you create block level // scope and don't actually create a new property on // the Global object, but with var, you do. var mode = "portfolio"; document.addEventListener('keydown',(event) => { // Within an event handler, "this" is a reference to the // object that triggered the event. But, within an Arrow // function, this is unchanged from whatever it had been // prior to the invocation of the arrow function. In this // case, the window, but if your Global is declared with // const or let, you'll get block scope and won't create // a true global property. With "var" (as I've shown above) // you will: console.log(this.mode, event.key); if(event.key === 'ArrowUp' || event.key === 'ArrowDown'){ modeToggle(); } }) const modeToggle = function() { console.log(`mode toggle called, current mode is ${mode}`); if(mode == "portfolio") { mode ="blog"; } else if(mode == "blog"){ mode ="portfolio"; } console.log(mode); }

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