understanding the javascript global namespace and closures

前端 未结 4 1264
闹比i
闹比i 2020-12-04 15:49

I\'m trying to improve my understanding of the global namespace in javascript and I\'m curious about a few things:

  1. is there a \"GOD\" (i.e. a parent) object

4条回答
  •  萌比男神i
    2020-12-04 16:22

    1. Yes, in a browser environment the "god object" is window. It's typically called the global object, not god object though ;) In non-browser environments such as nodejs, the global object may use some other name than window.

    2. If you put everything as globals, you risk running into colliding names. There is also the matter of encapsulation - in other words, by putting variables into only the scope where it's needed, your code is usually better off.

    3. Yep, this is pretty much the preferred approach. You can also use IIFE's

提交回复
热议问题