在 JavaScript 中,哪些代码在运行时执行,哪些代码在解析时执行?
特别是对于对象,我不明白对象的哪些部分在初始化之前运行,哪些部分在初始化时运行以及哪些部分在初始化后运行。
编辑:似乎解析时间是错误的词。我想我应该提出这样一个问题:“在两次读取中,第一遍读取什么,第二遍读取什么?”
With objects especially, I don't understand what parts of the object run before initialization, what runs at initialization and what runs sometime after.
EDIT: 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?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
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:
but the following doesn't
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.
与 C++ 不同,不可能在 Javascript 解析器中运行逻辑。
我怀疑您是在询问哪些代码立即运行以及哪些代码在创建每个对象实例时运行。
答案是,您调用的函数中的任何代码只会在调用该函数时运行,而函数外部的任何代码都会立即运行。
Unlike C++, it is not possible to run logic in the Javascript parser.
I suspect that you're asking which code runs immediately and which code runs when you create each object instance.
The answer is that any code in a function that you call will only run when you call the function, whereas any code outside of a function will run immediately.
不确定你具体问什么,所以我只是分享我所知道的。
JavaScript 函数是“预加载”并存储在浏览器的内存中,这意味着当您在页面的最后声明函数并在最开始调用它的代码时,它将起作用。
请注意,全局变量(即在函数外部分配的任何变量)不会预加载,因此只能在声明后使用。
函数之外的所有命令都将按照它们出现的顺序进行解析。
JavaScript 并没有真正的“运行时”,它只能响应事件或通过全局计时器执行代码。任何其他代码都将被解析并“忘记”。
Not sure what you ask exactly so I'll just share what I know.
JavaScript functions are "pre loaded" and stored in the browser's memory which means that when you have function declared in the very end of the page and code calling it in the very beginning, it will work.
Note that global variables, meaning any variable assigned outside of a function, are not preloaded, so can be used only after being declared.
All commands outside of a function will be parsed in the order they appear.
JavaScript doesn't really have "runtime", it can only respond to events or have code executed via global timers. Any other code will be parsed and "forgotten".
虽然JavaScript的直接祖先是Scheme,但JavaScript并没有继承宏,因此答案相当简单:在解析期间永远不会运行任何代码。
While JavaScript's direct ancestor is Scheme, JavaScript didn't inherit macros, so the answer is fairly simple: there is never any code run during parse time.
粗略地说,解释器首先获取所有变量和函数,然后将它们提升并执行。
有关更多详细信息,我希望这些链接可能有所帮助:
Roughly speaking, Interpreter gets all variables and functions first, and then they get hoisted and executed.
For more detail, I hope these links might be helpful: