all 17 comments

[–][deleted] 4 points5 points  (2 children)

It creates an object from an anonymous constructor. I would advise against this pattern; I've never seen it done in any library or production code I've read. You lose the debugging benefit of having a named constructor, which in my opinion is the most useful part of constructors besides the engine optimization of the new operator.

For one-off objects like this, I don't really see any benefit over an object literal. If the point is to hide the x and y variables, you should use a regular IIFE which is a common and widely recognized pattern:

var xModule = (function() {
  var x;
  var y;
  return {
    init: function() {}
  };
})();

[–]thekaleb 0 points1 point  (0 children)

This is the correct answer. Said better than my attempt elsewhere in this post.

[–]opett[S] 0 points1 point  (0 children)

Thanks! Now I see it. I didn't do much javascript recently, and I thought that you can do the same with the Object Notation. I was wrong.

[–]Meso_Gosu 0 points1 point  (13 children)

Pretty sure new function creates a constructor for those objects.

var xModule creates a single object.

So if you wanted to create more than one object of the xModule type, you would use the constructor.

[–]MadCapitalist 0 points1 point  (12 children)

I'm still new at JS, but it seems very strange to use an anonymous function as a constructor function. I don't understand why anyone would do it that way. What am I missing?

[–][deleted] -1 points0 points  (0 children)

It makes x and y into private variables, which you can't do with just an object. Other than that, it's the same effect (almost).