【问题标题】:Why global scope can not be accessed in this case? [duplicate]为什么在这种情况下无法访问全局范围? [复制]
【发布时间】:2022-01-19 22:52:28
【问题描述】:

我最近遇到了这个问题。我可以通过这个问题,但我没有得到它背后的概念。 如果您尝试 sn-p,您会看到发生了什么。谁能解释一下?

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>

【问题讨论】:

  • 内容丰富。谢谢。 @Rounin 的回答更清晰、更简短 IMO。

标签: javascript


【解决方案1】:

直截了当的答案是:

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

见:

const

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

来源: 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

【讨论】:

    【解决方案2】:

    问题在于您实际上是在调用一个值/变量(例如,const func2 = 可以以 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>

    【讨论】:

      【解决方案3】:

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

      如果我错了,请纠正我。

      【讨论】:

      • 这不是真的。 func2也是一个可调用函数,它不保存执行函数的值。
      • @BrianThompson 很有趣,感谢您的指正。
      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2019-01-22
      • 2012-12-14
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2016-07-29
      相关资源
      最近更新 更多