title: Subclass factory in AngularJS with member variables
body: <p>I have tens of AngularJS Factories which have a lot in common. So I'm trying to make a base class and subclass it.</p>
  
  <p>But I've noticed that the subclasses are sharing member variables of the base class.</p>
  
  <p>I've made an example on <a href="http://jsbin.com/doxemoza/2/edit" rel="nofollow">http://jsbin.com/doxemoza/2/edit</a>, the code is also posted here:</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"&gt;&lt;/script&gt;
  &lt;meta charset=utf-8 /&gt;
  &lt;title&gt;JS Bin&lt;/title&gt;
  &lt;/head&gt;
  &lt;body ng-app="demo" ng-controller="MainCtrl"&gt;
    &lt;p&gt;ChildService: {{value1}}&lt;/p&gt;
    &lt;p&gt;AnotherChildService : {{value2}}&lt;/p&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>JavaScript:</p>
  
  <pre><code>angular.module('demo', []);
  
  var demo = angular.module('demo').controller('MainCtrl', function ($scope, ChildService, AnotherChildService) {
    $scope.value1 = ChildService.getPrivateVar();
    $scope.value2 = AnotherChildService.getPrivateVar();
  });
  
  var Base = function () {
  
    var Service = {};
  
    Service.privateVar = 0;
  
    Service.setPrivateVar = function (value) {
      Service.privateVar = value;
    }
  
    Service.getPrivateVar = function () {
      return Service.privateVar;
    }
  
    return Service;
  };
  
  demo.factory('BaseService', Base)
  
  
  demo.factory('ChildService', function (BaseService) {
    var ChildService = Object.create(BaseService);
    ChildService.setPrivateVar(1);
    return ChildService;
  });
  
  demo.factory('AnotherChildService', function (BaseService) {
    var AnotherChildService = Object.create(BaseService);
    AnotherChildService.setPrivateVar(2);
    return AnotherChildService;
  });
  </code></pre>
  
  <p>My expected output is:</p>
  
  <pre><code>ChildService: 1
  
  AnotherChildService : 2
  </code></pre>
  
  <p>But instead I get:</p>
  
  <pre><code>ChildService: 2
  
  AnotherChildService : 2
  </code></pre>
  
  <p>I think <code>ChildService</code> and <code>AnotherChildService</code> are sharing the same <code>privateVar</code>, so I got the same value for them.</p>
  
  <p>How should I change the code to make them use different instance of <code>privateVar</code>?</p>
  
  <p>Thanks</p>