在运行时对函数声明进行解析和执行

克莱文·德利梅塔(Klevin Delimeta)

因此,在像JavaScript这样的解释性语言中,我们有:

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

console.log(x); // print statement

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

我的问题是:

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

PS我已经阅读了一些有关功能提升的内容,但仍然不了解。

damitj07

希望这会帮助我尝试简要解释我的答案。

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

  • 创建阶段:此阶段创建所有范围,变量和函数。还设置“ 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.

这只是实际情况的简短概述。我建议您对本文进行详细了解。以及对MDN文档的一些引用:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章