Clarify one JavaScript scoping regarding page 199 of Nicholas's "Maintainable JavaScript"

StackOverflow https://stackoverflow.com/questions/20353171

  •  25-08-2022
  •  | 
  •  

Question

In Appendix A, page 199, when discussing using "use strict", it goes like this:

If you want strict mode to apply to mulitple functions without needing to write "use strict" multiple times, use immediate function invocation:

//good
(function() {
    "use strict";

    function doSomething() {
        // code
    }

    function doSomethingElse() {
        // code
    }

}());

My question is, if this is what the whole anonlymous function looks like, then probably there is no effect (to the rest) of invoking it immediately? Because only two functions are declared within the anonymous function but it's neither called from within there (so the two functions cannot make any side effects to the rest of the world), nor returned to the outside so their references are lost.

Probably, I just want to confirm, that the code snippet is only intended to show the use of "use strict", so it simply omitted either the calls to, or return of, these two functions?

Thanks,

/bruin

Was it helpful?

Solution 2

I think you are correct. This example is not a complete one because it will never call the functions defined in it. The example is just meant to illustrate how to apply "use strict" across a specific set of functions. If you wanted to extend it a bit so that the functions are exported, you could do something like this:

var myModule = (function() {
    "use strict";

    function doSomething() {
        // code
    }

    function doSomethingElse() {
        // code
    }

    return {
        doSomething: doSomething,
        doSomethingElse: doSomethingElse
    };

}());

myModule.doSomething();
myModule.doSomethingElse();

OTHER TIPS

The idea is that the IIFE encloses all of your code, not just those functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top