[英]Using `const` to declare an ES6 function doesn't make it globally available but `var` does
I'm trying to make a function available everywhere once that script is loaded:一旦加载了该脚本,我就会尝试在任何地方提供一个函数:
"use strict";
const myFunction = () => {}
But when I try to call myFunction()
from another script it tells me that it doesn't exist, even though the script was loaded.但是当我尝试从另一个脚本调用
myFunction()
,它告诉我它不存在,即使脚本已加载。 If I change const
to var
, it works.如果我将
const
更改为var
,它会起作用。
Funnily enough, I've written code like this for a long time and it just appeared now, yet I'm architecturing the same way.有趣的是,我已经写了很长时间这样的代码,它现在才出现,但我正在以同样的方式构建。
Why is that?这是为什么?
First, strict mode makes it impossible to accidentally create global variables.
首先,严格模式使意外创建全局变量成为不可能。 In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript).
在正常的 JavaScript 中,在赋值中错误输入变量会在全局对象上创建一个新属性并继续“工作”(尽管未来可能会失败:可能,在现代 JavaScript 中)。 Assignments, which would accidentally create global variables, instead throw an error in strict mode.
赋值会意外创建全局变量,而在严格模式下会引发错误。
Ergo, remove 'use strict'
.因此,删除
'use strict'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.