0

I am trying to create a javascript library. There are two apparent ways of doing this.

The first way uses new:

var myLib = new function(){

    this.square = function(x){
        return x*x;
    };

}();

The other way is to return an object:

var myLib = function(){

    function square(x){
        return x*x;
    };

    return {square:square};

}();

Is one way preferable to the other, or is it a matter of personal preference.

Joshua
  • 2,431
  • 15
  • 23
  • Either way, you've got an object, since a function is an object, so it seems to me that the second style is just hiding the fact that the 'library' is-a Function. Which aesthetically has benefit, but IMO isn't worth the extra code and effort to keep everything synnced. As far as I see, you could always go back and do it the second way and it would be compatible if all the usages were 'well behaved'. So I'd start with the first and if you find some reason to go the second route, there's nothing stopping you. – zanerock Feb 28 '14 at 23:01
  • possible duplicate of [Constructor function vs Factory functions](http://stackoverflow.com/questions/8698726/constructor-function-vs-factory-functions) – Alexander Mar 13 '14 at 11:52

1 Answers1

-1

Check this topic please (Constructor function vs Factory functions): Constructor function vs Factory functions

Community
  • 1
  • 1
Alexander
  • 7,484
  • 4
  • 51
  • 65
  • If the question is exactly the same, please flag the question as a duplicate (flag -> duplicate -> insert URL -> flag question) instead of answering the question with simply a link to another question. – Qantas 94 Heavy Feb 28 '14 at 23:18