为什么在这种情况下不能访问全局范围



我最近遇到了这个问题。我可以通过这个问题,但我没有理解它背后的概念。如果你试一下这个片段,你就会明白发生了什么。有人能解释一下吗?

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>

简单的答案是:

letconst初始化的全局变量不成为window的属性。

参见:

const

全局常量不会成为window对象的属性,这与var变量不同

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

和:

let

const一样,let在全局声明时(在最顶部的作用域中(不会创建window对象的属性。

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

我对JS不是很有经验,但我相信这是因为第一个函数实际上是一个可以多次重用的函数,而第二个函数是lambda函数,目的是将值返回并存储(但不是重新计算(到func2变量中。

如果我错了,请纠正我。

问题是您实际上在调用一个值/变量(例如,const func2 =可能以int结尾。(您需要将函数本身int传递给window[Functioname]()格式。

您可以通过二阶函数调用来完成此操作,请参见下文。

顺便说一句,纽扣不错。

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>

最新更新