1

I've got this code:

var x = function(){
    return {
        x: function(name){
            this.name = name;
        }
    }
}();

var z = new x.x ("jaga");
console.log(z);

and my question is why do I need to use:

}();

at the end of function to make it a constructor?

OskiBoski
  • 15
  • 3
  • 4
    The code, as shown, doesn't make any sense. The IIFE makes things more complicated for no apparent reason. Better to just use the object literal form when defining `x` – CertainPerformance Nov 16 '19 at 07:55
  • Nearly all native functions are constructors. The `()` is needed to make it an IIFE (the second "I" is for "invoked"), otherwise it's just a function expression. – RobG Nov 16 '19 at 07:57
  • self-invoking function look at this https://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript – Jayakumar Thangavel Nov 16 '19 at 08:09
  • `why do I need to use` - without the `()` it's not an IIFE – Bravo Nov 16 '19 at 08:11

1 Answers1

0

The advantage of an IFFE is that it takes the code inside, out of the global scope. So your code can not have unexpected interactions with other code on your page.

This is mostly useful to people who publish libraries and is not providing any benefit in your example.

These days this patten has been replaced in es6 with modules.

David Bradshaw
  • 11,859
  • 3
  • 41
  • 70
  • Regardless if an IIFE is used to define the `x` variable here or not, exactly the same variables will be "exposed" to the rest of the page - that is, the `x` variable, and nothing else. The IIFE serves no purpose, because there's no scope to protect. – CertainPerformance Nov 16 '19 at 22:56