In JavaScript, what code executes at runtime and what code executes at parsetime?
With object开发者_JS百科s 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?"
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;
}
but the following doesn't
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.
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.
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".
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:
- http://adripofjavascript.com/blog/drips/variable-and-function-hoisting
- https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
精彩评论