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

时间:2018-03-18 13:24:25

标签: javascript function declaration

因此,在解释性语言中,如javascript,我们有:

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

console.log(x); // print statement

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

我的问题是:

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

P.S我已经阅读了有关功能提升的内容,但仍然不理解。

1 个答案:

答案 0 :(得分:2)

希望这有助于我简要解释一下我的答案。

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.

这只是对实际情况的简短概述。我建议您this article获取详细信息。 以及对MDN文档的一些引用: