[英]Why global scope can not be accessed in this case?
I faced this issue recently.我最近遇到了这个问题。 I could pass the problem, but I didn't get the concept behind it.我可以通过这个问题,但我没有得到它背后的概念。 If you try the snippet, you see what's going on.如果您尝试该片段,您会看到发生了什么。 Can someone explain it?有人可以解释一下吗?
function func1() { console.log('Func1 executed.'); }; const func2 = () => { console.log('Func2 executed.'); }; const test = () => { window['func1'](); //Working window['func2'](); //Not working };
button { width: 200px; padding: 20px; font-size: large; cursor: pointer; border: 0; background: linear-gradient(to top right, gray, silver); color: white; border-radius: 7px; box-shadow: 0px 5px 7px silver; text-shadow: 0px 2px 2px rgba(0,0,0,0.5); }
<button onclick='test()'>Execute</button>
I'm not very experienced with JS, but I believe is because the first one is actually a function that can be reused multiple time, where the second one is lambda function with the purpose to returning and storing a value (but not recompute) into the func2 var.我对JS的经验不太经验,但我相信是因为第一个实际上是function可以重复使用多个时间,第二个是Z945F3FC449518A73B9B9B9F5F5F5F32868DB4666666666666666666666666666666666666666666666666666666666C.ZC11C4211C421215ABER TOBEN func2 变量。
Correct me if I'm wrong.如我错了请纠正我。
The straightforward answer is:直截了当的答案是:
Global variables instantiated with let
and const
do not become properties of window
.用let
和const
实例化的全局变量不会成为window
的属性。
The issue is that you are really calling a value/variable ( const func2 =
could end with a int for example.) You need to pass a function itself int tohe format window[Functioname]()
.问题是您实际上是在调用一个值/变量(例如, const func2 =
可以以 int 结尾。)您需要将 function 本身传递给格式window[Functioname]()
。
You can do this through 2nd degree function calling, see below.您可以通过 2nd degree function 调用来做到这一点,见下文。
Nice button by the way.顺便说一句,按钮不错。
function func1() { console.log('Func1 executed.'); }; const func2 = () => { console.log('Func2 executed.'); }; function func3(){ func2(); } const test = () => { window['func1'](); //Working window['func3'](); //Working window['func2'](); //Not working };
button { width: 200px; padding: 20px; font-size: large; cursor: pointer; border: 0; background: linear-gradient(to top right, gray, silver); color: white; border-radius: 7px; box-shadow: 0px 5px 7px silver; text-shadow: 0px 2px 2px rgba(0,0,0,0.5); }
<button onclick='test()'>Execute</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.