0
var Person = function() {
    function Person(name) {
        this.name = name;
    }

    Person.prototype.getName = function() {
        return this.name;
    };
    console.log("called")
    return Person;
}();
var p = new Person('John');
console.log('Person 1 name: ' + p.getName());

Here, Person is assigned something as (function(){}()) syntax, what is this syntax about and what is it doing, Please someone explain this... I saw this code somewhere and I am not able to understand where the parenthesis after function syntax (function(){}()) came from and what are they doing.

On removing the second set of parenthesis it stops behaving as a constructor, Why so

Ayush Agrawal
  • 69
  • 1
  • 1
  • 5
  • possible a duplicate https://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript – sitaram9292 Oct 09 '18 at 10:42
  • This is a self-invoking function. You can find hundreds of articles about it on google. – Cata John Oct 09 '18 at 10:43
  • As some comments and answers in the dupe state, the standard name for this is "Immediately Invoked Function Expression" (or IIFE); it even has its own tag: [tag:iife] – Amadan Oct 09 '18 at 10:48

1 Answers1

1

The first () is declaring it as a function - this is where parameters passed in would go if there were any.

{} is where the logic is declared.

The second () calls the function immediately after it is defined, as opposed to it being called from somewhere else.

James Whiteley
  • 3,363
  • 1
  • 19
  • 46
  • Ok now I got it, Can you answer another query i.e.: When I remove the second `()` parenthesis then it no more works as a constructor, why so... – Ayush Agrawal Oct 09 '18 at 10:52
  • @AyushAgrawal First `()` is `definition`, Second `()` is `initialisation`. The function has to be initialised/executed for the inner logic to work. – Nishant Ghodke Oct 09 '18 at 10:58
  • @AyushAgrawal It will work fine without the second parentheses if you call it as `Person()`. See [here](https://jsfiddle.net/7gq3mrwx/) for a demo. – James Whiteley Oct 09 '18 at 11:00
  • `var Person = function() {` ` function Person(name) {` ` this.name = name;` `}` `Person.prototype.getName = function() {` ` return this.name;` ` };` `console.log("called")` ` return Person;` `}();` `var p = new Person('John');` `console.log('Person 1 name: ' + p.getName());` @JamesWhiteley In this code if i remove the second () it no more works as a constructor – Ayush Agrawal Oct 09 '18 at 11:07