Angularjs服务是单例吗?

前端之家收集整理的这篇文章主要介绍了Angularjs服务是单例吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
referenceI读:

Lastly,it is important to realize that all Angular services are
application singletons. This means that there is only one instance of
a given service per injector.

但是用这个简单的代码似乎不是一个单例

  1. 'use strict';
  2. angular.module('animal',[])
  3. .factory('Animal',function(){
  4. return function(vocalization){
  5. return {
  6. vocalization:vocalization,vocalize : function () {
  7. console.log('vocalize: ' + this.vocalization);
  8. }
  9. }
  10. }
  11. });
  12. angular.module('app',['animal'])
  13. .factory('Dog',function (Animal) {
  14. return Animal('bark bark!');
  15. })
  16. .factory('Cat',function (Animal) {
  17. return Animal('meeeooooow');
  18. })
  19. .controller('MainCtrl',function($scope,Cat,Dog){
  20. $scope.cat = Cat;
  21. $scope.dog = Dog;
  22. console.log($scope.cat);
  23. console.log($scope.dog);
  24. //$scope.cat = Cat;
  25. });

我有点困惑你能解释我什么事?

更新1
可能我不是在棚子里最锋利的工具
但是在@Khanh TO回复它会是一个更好
解释在参考它不是很清楚。

更新2

  1. 'use strict';
  2. angular.module('animal',function(){
  3. return {
  4. vocalization:'',vocalize : function () {
  5. console.log('vocalize: ' + this.vocalization);
  6. }
  7. }
  8.  
  9. });
  10. angular.module('dog',function (Animal) {
  11. Animal.vocalization = 'bark bark!';
  12. Animal.color = 'red';
  13. return Animal;
  14. });
  15.  
  16. angular.module('cat',['animal'])
  17. .factory('Cat',function (Animal) {
  18. Animal.vocalization = 'meowwww';
  19. Animal.color = 'white';
  20. return Animal;
  21. });
  22. angular.module('app',['dog','cat'])
  23. .controller('MainCtrl',Dog){
  24. $scope.cat = Cat;
  25. $scope.dog = Dog;
  26. console.log($scope.cat);
  27. console.log($scope.dog);
  28. //$scope.cat = Cat;
  29. });

BOOM这是一个单身!

更新3

但如果你喜欢

  1. 'use strict';
  2. angular.module('animal',function (Animal) {
  3. function ngDog(){
  4. this.prop = 'my prop 1';
  5. this.myMethod = function(){
  6. console.log('test 1');
  7. }
  8. }
  9. return angular.extend(Animal('bark bark!'),new ngDog());
  10. })
  11. .factory('Cat',function (Animal) {
  12. function ngCat(){
  13. this.prop = 'my prop 2';
  14. this.myMethod = function(){
  15. console.log('test 2');
  16. }
  17. }
  18. return angular.extend(Animal('meooow'),new ngCat());
  19. })
  20. .controller('MainCtrl',Dog){
  21. $scope.cat = Cat;
  22. $scope.dog = Dog;
  23. console.log($scope.cat);
  24. console.log($scope.dog);
  25. //$scope.cat = Cat;
  26. });

有用

它是单例,只有一个对象,但是注入到许多地方。 (通过引用方法传递对象)

所有你的Animal都是指向同一个动物对象的对象指针,这是你的情况下的一个函数。您的Cat和Dog是由此函数构建的对象。

猜你在找的Angularjs相关文章