0
 (function(window){
       var helloSpeaker = new Object ();
       var speakWord = "Hello";
       helloSpeaker.speak = function (name) {
           console.log(speakWord + " " + name);
       }
       window.helloSpeaker = helloSpeaker;
    })(window);

From the snippet above, I understand that it's an immediately invoked function expression(IIFE) which its major purpose is to protect the private variable 'speakWord'. I'm also awared that we need to expose the object 'helloSpeaker' to the window scope which is the reason for window.helloSpeaker = helloSpeaker;. However, i seem not to understand why we need to pass window as an argument to the function knowing fully well that it's still in the window environment where the function is invoked. Please why do I need to pass window to the function?

  • Does this answer your question? [How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?](https://stackoverflow.com/questions/2716069/how-does-this-javascript-jquery-syntax-work-function-window-undefined) – Anurag Srivastava Mar 27 '20 at 16:07
  • Otherwise you could not assign helloSpeaker to window because that function is within an other function "()" with no name – Giacomo Scarpino Mar 27 '20 at 16:29
  • @GiacomoScarpino pls confirm your statement because from what I understood in this post: [https://stackoverflow.com/questions/2716069/how-does-this-javascript-jquery-syntax-work-function-window-undefined], the major reason we pass the window as object to a function is to make the program run faster – olubiyo elijah Mar 29 '20 at 07:18
  • @olubiyoelijah It doesn't speed up anything. When you write a function that immediately executes, like the above, everything that lives in that function is kind of isolated from the rest of the program, it won’t leak out. It acts like a module, a container for the code. – Giacomo Scarpino Mar 29 '20 at 21:49

0 Answers0