简体   繁体   中英

Changing addEventListener variables' scope to global

I want variables from addEventListener functions to be taken into account when calculating the final, global variable. I know that by default they remain in local / block / function scope. Can this be somehow worked around? I am trying to calculate price (global variable) based on local variables from click events (input, drop-down list and 2 checkboxes). When I declare it I get a message that local variables are not defined. It's understandable because event hasn't happened yet. Even after it does I can read updated values of local variables in browser console but global variable still remains undefined.

At the top of your file, declare the global var you want to mutate:

var EvilGlobalPriceVariable = 0

Then in the handlers, mutate that. Do that for every variable you want to affect in the handlers. Best to make it an object if you have more than one:

var EvilGlobalState = {
   mutateMeHandlers: 0,
   mutateMeToo: 0
}

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