[英]Changing addEventListener variables' scope to global
I want variables from addEventListener functions to be taken into account when calculating the final, global variable.我希望在计算最终的全局变量时考虑 addEventListener 函数中的变量。 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).
我正在尝试根据点击事件(输入、下拉列表和 2 个复选框)中的局部变量来计算价格(全局变量)。 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.