简体   繁体   English

后续的javascript函数中未定义全局变量

[英]Global variable undefined in javascript function that follows

I had some code that essentially was like this: 我有一些基本上是这样的代码:

TestFunction();
const pi = 3.14;

function TestFunction()
{
    alert("pi="+pi);
}

The code failed because 'pi' was undefined. 代码失败,因为未定义“ pi”。 I scratched my head for a long time but then realized that the code was not being parsed linearly. 我挠了很长时间,但后来意识到代码不是线性解析的。 When the function was called, the function "TestFunction" was parsed, but the constant had not yet been parsed. 调用该函数时,已解析函数“ TestFunction”,但尚未解析该常量。

This occurred with Safari and Chrome. 这是在Safari和Chrome中发生的。 I don't know if all browsers would parse in the same way. 我不知道所有的浏览器是否都将以相同的方式进行解析。 It might work with some. 它可能与某些人一起工作。

Moving the definition of the constant before the first call to the function solved the problem. 在第一次调用该函数之前将常量的定义移动即可解决该问题。

const pi = 3.14;

TestFunction();

function TestFunction()
{
    alert("pi="+pi);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM