Javascript 在运行时,是否解析并执行函数声明
因此,在解释语言(如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语句?在解析函数声明之前还是之后?如果它在之前被
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文档的一些参考: