Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why top level functions are created as methods of window in JavaScript? [closed]

Tags:

javascript

dom

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?

like image 992
Geek Avatar asked May 27 '13 18:05

Geek


2 Answers

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?

like image 146
Dory Zidon Avatar answered Oct 01 '22 20:10

Dory Zidon


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.

like image 44
bfavaretto Avatar answered Oct 01 '22 19:10

bfavaretto