JavaScript编译序列在这段代码中是如何工作的



为什么将错误代码行放在底部,运行程序的其余部分。但是把它放在这里不会运行任何一个函数,这会导致错误。

const A = "A";
let F;
function doStuff(B) {
console.log(B);
const C = "C";
let H = "H";
if (1 + 1 === 2) {
const D = "D";
H = "something else";
}
console.log(H);
F = "F";
}
console.log(B); // I know it has error
let E = 0;
while (E < 3) {
E++;
console.log(A); //But why this
}
doStuff("B"); // and this
console.log(E); // and this is not working unless I remove that line or place that in the bottom of the code.
变量B没有在任何地方定义,所以它当然会对你大喊大叫。

const A = "A";
let F;
function doStuff(B) {
console.log(B);
const C = "C";
let H = "H";
if (1 + 1 === 2) {
const D = "D";
H = "something else";
}
console.log(H);
F = "F";
}
//console.log(B);  <-- What is B, it is not defined anywhere so Javascript will yell at you becasue it doesn't know what it is
let E = 0;
console.log(E); //this works here because E is initialized
while (E < 3) {
E++;
console.log(A); //variable A defined at the top of the code can be accessed here so this will work
}
doStuff("B"); // and this
console.log(E); //it will also works here

至于为什么将console.log(B(放在底部会运行部分代码,而不是像C++或C#那样直接抛出错误,JavaScript是一种解释语言,而不是编译语言。这意味着,当你运行一段代码时,会有一个intelpreter,它会逐一读取每一行代码,然后对其进行intelpret。Javascript中根本没有编译步骤。

例如,这仍然将输出";你好"当浏览器读取第一行时,解释它,然后运行它。它不知道第二行发生了什么

console.log("Hello");
console.log(A)

最新更新