Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?"

like image 489
randomable Avatar asked Oct 26 '10 12:10

randomable


3 Answers

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.

like image 141
Gareth Avatar answered Nov 19 '22 19:11

Gareth


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.

like image 29
SLaks Avatar answered Nov 19 '22 21:11

SLaks


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".

like image 4
Shadow Wizard Hates Omicron Avatar answered Nov 19 '22 21:11

Shadow Wizard Hates Omicron