I have a multitude of AngularJS Factories that share similar characteristics. To streamline my code, I am attempting to create a base class and then subclass it.
However, I've encountered an issue where the subclasses are inadvertently sharing member variables with the base class.
To illustrate this problem, I have provided an example on http://jsbin.com/doxemoza/2/edit. You can also view the code below:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body ng-app="demo" ng-controller="MainCtrl">
<p>ChildService: {{value1}}</p>
<p>AnotherChildService : {{value2}}</p>
</body>
</html>
JavaScript:
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;
});
In my desired output, I expect:
ChildService: 1
AnotherChildService : 2
However, the actual output is:
ChildService: 2
AnotherChildService : 2
It appears that both ChildService
and AnotherChildService
are sharing the same privateVar
, resulting in the duplication of values.
How can I modify the code to ensure that they utilize separate instances of privateVar
? Any suggestions would be greatly appreciated.
Thank you