Skip to content

Instantly share code, notes, and snippets.

@endorama
Last active August 29, 2015 14:00
Show Gist options
  • Save endorama/11399642 to your computer and use it in GitHub Desktop.
Save endorama/11399642 to your computer and use it in GitHub Desktop.
AngularJS class design pattern
(function() {
"use strict";
var module = angular.module('foo');
module.factory('fooFactory', [
function() {
// Define the constructor function.
function FooClass() {}
// Inherit from Superclass prototype, if is the case
// FooClass.prototype = Object.create(Superclass.prototype);
// Define the "instance" methods using the prototype
// and standard prototypal inheritance.
FooClass.prototype.instanceMethod = function() {};
// Define the "class" / "static" methods. These are
// utility methods on the class itself; they do not
// have access to the "this" reference.
FooClass.staticMethod = function() {};
// Return constructor - this is what defines the actual
// injectable in the DI framework.
return (FooClass);
}
]);
}());
(function() {
'use strict';
angular
.module('foo')
.service('FooService', Service);
Service.$inject = [ ];
function Service() {
var _private = null;
// default constructor, run before return
var __construct = function() {}.bind(this);
// instance methods
this.fooInstanceMethod = function() {};
// private methods
var _privateMethod = function() {};
// no room for 'static' methods, because a service is invoked using new
// Service(), so there should be no reason to use a static method
__construct();
return this;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment