Node.js global variables

前端 未结 6 1523
耶瑟儿~
耶瑟儿~ 2020-11-22 13:06

I asked here: Does Node.js require inheritance?

And I was told that I can set variables to the global scope by leaving out the variable.

This does not

6条回答
  •  一整个雨季
    2020-11-22 13:33

    I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:

    // Some global/configuration file that gets called in initialisation
    
    global.MyError = [Function of MyError];
    

    Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:

    1. Define the Error class in the first place
    2. In the script where you're throwing it
    3. In the script where you're catching it

    Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.

提交回复
热议问题