0

got this function:

function Something(name){
   this.name = name;
}

var createSomething = (function() {
  function F(args) {
    return Something.apply(this, args);
  }
  F.prototype = Something.prototype;

  return function() {
    return new F(arguments);
  }
})();

var x = createSomething('abc');

Why does createSomething have to be a self-invoking function?

I noticed when leaving the invoking brackets (), x will just be empty. But why?

It invokes "unasked" at the initialization of the javascript and then runs again once "asked" for. But what's the point of the first run? Does it straight assign the "this" correctly, or what's the point of use?

raina77ow
  • 103,633
  • 15
  • 192
  • 229

1 Answers1

4

Why does createSomething have to be a self-invoking function?

createSomething is not a self invoking function, but it stores the result of a self invoking function. Self invoking functions are also know as IIFE's in javascript world. I suggest you to read this to get a better understanding.

I noticed when leaving the invoking brackets (), x will just be empty. But why?

It will not be empty but rather will point to an unnamed function object. probably you meant it will not give the expected result.

It invokes "unasked" at the initialization of the javascript and then runs again once "asked" for. But what's the point of the first run? Does it straight assign the "this" correctly, or what's the point of use?

On the first run the unnamed function creates a new function (which is then assigned to createSomething). This newly created function (which is referred to by createSomething) is then called with 'abc', there is no second run of the IIFE.

The other thing to note is function F is only accessible to the newly created function. The underlying mechanism for this is called closures. I would suggest you to understand these underlying concepts (linked in this answer) to get a better picture.

Community
  • 1
  • 1
Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
  • I understand. Thank you. I've read about the module pattern before, however, whenever someone states "it is created within a module pattern to not pollute the global namespace",it sounds a bit weird. as, in case it is defined within a function , no matter if it's a module or not, it won't pollute the namespace anyways,except it is defined above the context and not defined within a new function / module. Or did i catch up something wrong there? – DavidCockerfield Sep 14 '14 at 14:59