简体   繁体   中英

Angularjs Services, Factories, and Prototypical inheritance

From what I've read and tested, avoiding constructors and leveraging prototypical inheritance as much as possible has benefits. It's faster (not by much but I'm having to loop through +100,000's of items), allows for more flexibility, and is more native to JavaScript's philosophy.

My question then is how do you leverage an Angularjs Factory/Service to use prototypical inheritance rather than constructor logic suggested by the service?

Here is my example:

angular.module('components', [])
.service('Item', function() {
    var Item = function(val){
        this.func1 = function() {....};
        this.func2 = function() {....};
        this.func3 = function() {....};
         //... lots of functions
    }
    return Item; // @Flex, Forgot this, tnx
});

angular.module('main', ['components'])
.controller('MainCtrl', function(Item) {
    var items = [];
    _.each(largeArray, function(itm) { 
        items.push(new Item(itm));
    });
});

How can I change the service or factory to create items that inherit all functionality using prototypical inheritance instead? And since that's technically faster (I know not by much) & more native to the experience, why isn't it standard? Am I not understanding something about Angularjs?

Instead of

var Item = function(val){
    this.func1 = function() {....};
    this.func2 = function() {....};
    this.func3 = function() {....};
     //... lots of functions
}

you could use

var Item = (function(){
   var Item = function(val){
     // put attributes here not methods...
   }
   Item.prototype.func1 = function(){...};
   Item.prototype.func2 = function(){...};

   return Item;
})()

I think this is what you mean. This has nothing to do with angularjs though.. its just how you realize prototypical inheritance in a clean way.

Your example should do nothing btw, because you dont return anything from the service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM