Is there any reason to define module.exports using an IIFE?

后端 未结 2 521
刺人心
刺人心 2020-12-28 16:35

My team doesn\'t have any experienced JS developers, but we are writing a library in Node and got a suggestion from a real JS developer that \"We should make the js more mod

2条回答
  •  别那么骄傲
    2020-12-28 16:58

    Pretty much no difference. The whole idea of Node.js, using require, having modules, etc., is specifically to separate concerns. I'd say (cautiously) that if you're doing it right, you shouldn't be needing to worry about "polluting" any sort of global scope. Anything within module.exports lives in that module.

    When you're dealing with front-end stuff, that's when the global scope becomes something of a concern, because if a function or whatever isn't scoped (i.e., in an IIFE, or other function block), it has access to the global window object, and everything else has access to that function.

    a real JS developer

    Calling someone that is a red flag.

    not to pollute the global namespace and to make it more readable to new-comers

    If you're modularizing your code correctly, that shouldn't be a concern. There's a time and a place for IIFEs, but I see no reason why wrapping everything in an IIFE, which is already inside of a module, would somehow magically make the code "more modular" or any more readable to "new comers" than by simply using Node.js like it was designed:

    module.exports = function() { ... } // whatever
    

    and even if it did, they would be local to the module file and not global to the whole program that require()s it.

    You are correct. I'd take whatever he's saying with a grain of salt. Maybe he knows of some specific use-cases where his approach has been helpful to him in the past, so I'd ask him specifically about that to see what he says. Other than that, I feel like you're on the right track.

提交回复
热议问题