在JavaScript中,什么代码在运行时执行,哪些代码在分析时执行? [英] In JavaScript, what code executes at runtime and what code executes at parsetime?
问题描述
特别是对象,我不明白对象的哪些部分在初始化之前运行,什么在初始化时运行以及什么时候运行。
With objects especially, I don't understand what parts of the object run before initialization, what runs at initialization and what runs sometime after.
编辑:似乎那个解析时间错了。我想我应该制定一个问题在2遍读取中,第一遍读取什么,第二遍读取什么?
It seems that parsetime is the wrong word. I guess I should have formulated the question "In the 2-pass read, what gets read the first pass and what gets read the second pass?"
推荐答案
javascript文件以2遍读取方式运行。第一遍解析语法并收集函数定义,第二遍实际执行代码。通过注意以下代码可以看出这一点:
A javascript file is run in a 2-pass read. The first pass parses syntax and collects function definitions, and the second pass actually executes the code. This can be seen by noting that the following code works:
foo();
function foo() {
return 5;
}
但以下不是
foo(); // ReferenceError: foo is not defined
foo = function() {
return 5;
}
然而,这并不是很有用,因为没有第一遍中的任何执行。您无法使用此功能来更改逻辑。
However, this isn't really useful to know, as there isn't any execution in the first pass. You can't make use of this feature to change your logic at all.
这篇关于在JavaScript中,什么代码在运行时执行,哪些代码在分析时执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!