-
Is there a god (i.e. a parent) object?
Yes. More technically, it’s the global object that all these primitives are members of; it just happens that in the browser, the
window
object is the global object.> window.String === String; true
-
Why is it bad idea to have vars/functions on a global level?
Because if you’re adding lots of 3rd party libraries/ scripts, they all share the same global object, there’s the chance of name collisions. This is a real life problem with all the libraries which use
$
as an alias (jQuery, Prototype and more). -
If it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this?
x
shouldn’t be considered global. It’s part of the closure formed by declaring the child functions inside theparent()
function. The problem part of your snippet is thatparent()
is global; what happens if some other code re-declaredparent()
? This would be better:(function () { function parent(){ var x = 'some value'; function child1(){ x.someMethod() } function child2(){ x*something; } function child3(){ x+=something; child2() child1() } child3() } parent() }());
The fact
x
is accessible within the child functions isn’t bad; you should have written those functions yourself, so you should be aware of the existence ofx
. Bear in mind that if you re-declarex
within those child functions withvar
, you won’t affect thex
inparent()
.