OO inheritance for AngularJS factories

AngularJS  services and factories require a return object. As such, the parasitic combination inheritance calls mentioned in the previous post need to be changed a bit so that the return object from the call to the parent class is stored so that it can be returned from the child class in a way that Angular likes. Here’s what it looks like when using my ‘utility’ inheritance tools:

function QueryServiceFn2($http){
   var retObj = QueryServiceFn.call(this, $http);
   globalU.inheritPrototype(this, QueryServiceFn);
   return retObj;
}

So that works just fine. Closure also works the way that I think it should – methods referenced in the parent class have visibility to the ‘hidden’ parent objects. Here’s full example of inheriting a factory object (full version here – the child class is at the bottom of the file):

globalUtils.appMap.phpFactories2 = (function(globalU, base){
   "use strict";
   function QueryServiceFn($http){
      var retObj = base.call(this, $http);
      globalU.inheritPrototype(this, base);
      return retObj;
   }

   return{
      queryServicePtr: QueryServiceFn
   };
})(globalUtils, globalUtils.appMap.phpFactories.queryServicePtr);

To override a function, simply declare it normally and then set the pointer in retObj to point at the new version. The only thing to watch out for is that closure won’t hold. If you need access to an item in the base class that’s accessed through closure, you’ll probably have to copy it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s