0

I am having following example that shows the result achieved from a factory & a service. As per my knowledge, Factory always returns an object, while service always returns an instance of an object. Here, what is the difference in the 2 returned objects conceptually. Can someone clarify? (Particular to this scenario)

Snippet:

<html> 
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
</head> 
<body ng-app="myApp" ng-controller="myCtrl"> 
<script>
    //module declaration
    var app = angular.module('myApp',[]);
    //controller declaration
    app.controller('myCtrl', function($scope, myFactory, myService){
        $scope.name = "Peter";
        var a = myService;
        console.log(a);
        var b = myFactory;
        console.log(b);
    });
    //services declaration
    app.service('myService',function(){
        this.age = 15;
    });
    app.factory('myFactory',function(){
        var obj = {};
        obj.country = "USA";
        return obj;
    });
</script> 
</body> 
</html> 

Result:

enter image description here

Already Read:

AngularJS: Service vs provider vs factory

Community
  • 1
  • 1
Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • There's no such thing as 'an instance of an object'. It is an instance of constructor, and the function doesn't return anything. It is possible to return an object from constructor function, though it is not advisable. – Estus Flask Sep 26 '16 at 14:43

1 Answers1

1

Your understanding of Factory always returns an object, while service always returns an instance of an object is correct. To clarify the question regarding the specific html snippet you posted, in the console you can see the service is having a constructor, however no constructor of its own for factory.

enter image description here

rushi
  • 276
  • 1
  • 6