When we define a top level named function in Javascript, it becomes a method of the window object. What is the reason for this design decision?
Javascript always run in a particular global context. In a browser environment that is the window object, so when you define a global, you're actually adding it to window...
Here is another excellent stackoverflow answer explaining why this is so: Is window really global in Javascript?
What is the reason for this design decision?
I can't answer that, we'd have to ask the guy who designed the language, and the committee that maintains its specification. But maybe this will give you some insights: internally, variables (local or global) are always stored in "Lexical Environment" objects. So, they are always properties, and they even have their own properties (to mark them as read-only, non-deletable, etc.).
The environment objects are not exposed in browser JavaScript, except for the global object (as pointed out by squint in the comments, ECMAScript doesn't actually require that the global variable object be exposed, that's up to the implementation.)
It happens that it was decided that the global object is the same as the window object in browsers. Why? Again, I can't answer that. They just decided not to use a dedicated global
(or whatever) identifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With