As I was developing an AngularJS app, I started thinking about the use of factories in a different light. Instead of just returning plain objects, what if we used factories to create and return constructor functions like this:
app.factory("Foo", function() {
function Foo(bar, baz) {
this.bar = bar;
this.baz = baz;
...
}
Foo.prototype = {
constructor: Foo,
method1: function() { ... },
method2: function() { ... },
...,
methodn: function() { ... },
};
return Foo;
});
Initially, I found this approach elegant and object-oriented. However, upon further reflection, I began to question whether it might actually be considered an anti-pattern. While it works well within the confines of AngularJS, using these constructor functions outside of AngularJS environments presents challenges. It made me wonder if I was trying too hard to fit a square peg into a round hole, as JavaScript functions inherently behave like singletons and do not necessarily require additional handling for instantiation.
So, am I missing the mark with my use of AngularJS factories? Would exposing constructor functions globally serve me better? And more broadly, what are the factors that favor the use of AngularJS factories/services/providers compared to global objects or vice versa?