【问题标题】:When in run-time is the function declaration parsed and executed在运行时解析并执行函数声明
【发布时间】:2018-03-18 13:24:24
【问题描述】:

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

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

console.log(x); // print statement

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

我的问题是:

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

P.S 我读过一些关于函数提升的东西,但还是不明白。

【问题讨论】:

  • 提升意味着在第一次解析运行时将声明的变量和函数放在内存中,然后执行代码。因此,该功能有效地“提升到顶部”并且在代码执行时可用。 jsfiddle.net/bsp38yc9
  • 另见与IIF's的区别。
  • “提升到示波器顶部”。另见variable shadowing

标签: javascript function declaration


【解决方案1】:

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

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.

这只是对实际情况的简短概述。我建议this article 以获得详细的见解。 以及对 MDN 文档的一些参考:

【讨论】:

  • 非常有用且详细的答案。谢谢,帮了大忙。
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多