在运行时解析并执行函数声明

Kle*_*eta 4 javascript declaration function

所以在解释语言中,比如 javascript,我们有:

var x = doThis(); // function call, assign statement

console.log(x); // print statement

function doThis(){ //function declaration
 return "Hello World"; //return statement
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

何时(运行时)打印语句实际执行?在解析函数声明之前还是之后?如果它之前被执行,如何,因为没有编译器,代码会立即执行。

PS 我已经阅读了一些关于函数提升的内容,但仍然不明白。

dam*_*j07 5

希望这有助于我将尝试简要解释我的答案。

JS 运行时在执行上下文中执行每段代码。每个执行上下文有 2 个阶段:

  • 创建阶段:此阶段创建所有范围、变量和函数。还设置“this”上下文。
  • 执行阶段:这个阶段实际上是console.log( )通过发送机器可以理解的命令来执行类似语句的代码。

现在,当浏览器首次加载您的脚本时,它默认进入全局执行上下文。这个执行上下文也会有创建阶段和执行阶段。

现在考虑你的代码:

//Line 1
var x = doThis(); 
//Line 2
console.log(x); 
//Line 3
function doThis(){ 
  return "Hello World"; 
}
Run Code Online (Sandbox Code Playgroud)

这是解释器所做的事情的伪表示:

 // First Pass
 1.Find some code to invoke a function.
 2.Before executing the function code, create a context to execute in.
 3.Enter the Creation Stage:  
     - Create a scope chain
     - Scan for function declarations 
       // In your case, this is where *doThis()* is stored in the global scope
     - Scan for var declarations  
       // This is where *var x* is set to *undefined*
4. Run/interpret the function code in the context(Execution Stage)
  // Now as per the sequence line 1 will run and set *var x = "Hello World"*
  // And then followed by line 2 which will print "Hello World" to console.
Run Code Online (Sandbox Code Playgroud)

这只是对实际发生的事情的简短概述。我会推荐这篇文章以获得详细的见解。以及对 MDN 文档的一些参考: