【发布时间】:2014-07-09 05:45:33
【问题描述】:
我有数十个 AngularJS 工厂,它们有很多共同点。所以我正在尝试创建一个基类并对其进行子类化。
但我注意到子类共享基类的成员变量。
我在http://jsbin.com/doxemoza/2/edit上做了一个例子,代码也贴在这里:
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;
});
我的预期输出是:
ChildService: 1
AnotherChildService : 2
但是我得到了:
ChildService: 2
AnotherChildService : 2
我认为ChildService 和AnotherChildService 共享相同的privateVar,所以我得到了相同的值。
我应该如何更改代码以使它们使用 privateVar 的不同实例?
谢谢
【问题讨论】:
标签: javascript angularjs oop