KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
This is something I've been mulling over while creating an AngularJS app. When I first learned about AngularJS factories, I thought one clever usage of them would be to create and return a constructor function rather than a plain object, i.e. something like: 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; }); Then, you could inject the function into your controllers and call it with new . I found this aesthetically pleasing and OOP-y, but now I'm starting to think that it's actually an anti-pattern. The problem is that it works fine for when you're working within AngularJS-aware contexts, but once you want to, for instance, call the constructor from the console, use it in a Web Worker, or reuse the code in a non-AngularJS app, you start having to work around AngularJS rather than with it. I began to wonder if this approach was misguided insofar as functions in javascript already seem to be "singletons" and don't seem to need any help being instantiated. Am I misusing AngularJS factories? Would I be better served with constructor functions exposed to the global scope? More generally, are there specific factors which promote the usage of AngularJS factories/services/providers over global objects or vice versa?
Tags (comma-separated)
Save Edits
Cancel