在运行-时间是函数声明被解析和执行的时候

When in run-time is the function declaration parsed and executed

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

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

console.log(x); // print statement

function doThis(){ //function declaration
 return "Hello World"; //return statement
}

我的问题是:

打印语句何时真正执行?在解析函数声明之前还是之后?如果它之前执行过,如何执行,因为没有编译器,代码立即执行。

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

希望这对您有所帮助,我将尝试简要解释一下我的回答。

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

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

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

现在考虑您的代码:

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

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

 // 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.

这只是一个简短的概述,实际上 happens.I 会推荐 this article 以获得详细的见解。 以及对 MDN 文档的一些引用: