Search code examples
javascriptangularjsprototypeinstanceoftypeof

AngularJS get instance of factory object


Is there a way to check the instance of an object created by an AngularJS factory?

angular.module('so')
    .factory('UserFac', function () {
        return function (first, last) {
             return {
                 name : first + ' ' + last
             };
        }
    })
    .controller('UserCtrl', function (User) {
        var user = new UserFac('John', 'Doe');

        function isUser(userObj) {
            // your answer here...
        }

        if (isUser(user)) {
            // does not matter
        }
    });

Unfortunately I found no way to check the instance of the factory object by the usual JavaScript ways like:

user instanceof UserFac

or

typeof user === 'UserFac'

or

user.constructor === UserFac

or

user.prototype === UserFac

It looks like the internal AngularJS code for factories/services conceals the prototype/constructor property.

Websearch is quite painful, as (most of) all results deal with the difference between a service and a factory.

Thanks for your help!


Solution

  • One problem is that your constructor function is anonymous, another problem is that you're returning an object literal (which is not an instance of your constructor function, but an instance of Object constructor) from your constructor function.

    instanceof will work properly if you do it as shown below:

    angular.module('so', []);
    angular.module('so')
      .factory('UserFac', function() {
        function UserFac(first, last) {
         //--------^-- give it the factory name
          this.name = first + ' ' + last
         //-^-- use the object created internally using this keyword
        }
        return UserFac;
      })
      .controller('UserCtrl', function(UserFac) {
        var user = new UserFac('John', 'Doe');
        console.log(user instanceof UserFac)
      });