0

I would like to know how Javascript maintains a single global namespace. Does it have any linker which links all JS related to that page and maintains a single global namespace?

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
Vel
  • 409
  • 1
  • 5
  • 8
  • Read this: http://stackoverflow.com/questions/9773964/understanding-the-javascript-global-namespace-and-closures – Frank Tudor Apr 15 '13 at 20:16
  • This should help: http://stackoverflow.com/questions/9773964/understanding-the-javascript-global-namespace-and-closures – karthikr Apr 15 '13 at 20:16
  • Wouldn't it be much harder to keep each script element completely independent? Especially since they would all need to interact with the same DOM. – Quentin Apr 15 '13 at 20:20
  • @Quentin: Not really. Every ` – josh3736 Apr 15 '13 at 20:28

1 Answers1

2

The important thing to understand here is that all JavaScript in a page (whether inline or pulled in via <script src="...">) is essentially concatenated and executed in the same VM. There's no need to "maintain a single global namespace" because all code is evaluated in the same place and shares the same global object, window.

Remember, despite the fact that modern engines do compile JS to native code internally, JS is not a compiled language like C. Thus, there is no linker.

There is VM concept you might want to understand known as the context. The V8 VM supports running code that uses one global object alongside code that uses a different global object. This allows code running in an <iframe> to get its own global object but still access and call methods from the parent page's context.

josh3736
  • 139,160
  • 33
  • 216
  • 263