Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在运行时,是否解析并执行函数声明_Javascript_Function_Declaration - Fatal编程技术网

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

Javascript 在运行时,是否解析并执行函数声明,javascript,function,declaration,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语句?在解析函数声明之前还是之后?如果它在之前被

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

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

console.log(x); // print statement

function doThis(){ //function declaration
 return "Hello World"; //return statement
}
我的问题是:

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


另外,我读过一些关于函数提升的内容,但仍然不理解。

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

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文档的一些参考:


提升意味着在第一次解析运行中将声明的变量和函数放在内存中,然后执行代码。因此,该功能有效地“提升到顶部”,并在代码执行时可用。另请参见“吊至范围顶部”的区别。另请参阅。非常有用和详细的答案。谢谢你,帮了我很多忙。