简体   繁体   English

Angularjs服务,工厂和原型继承

[英]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. 它速度更快(不是很多,但我必须遍历+100,000的项目),具有更大的灵活性,并且更加符合JavaScript的哲学。

My question then is how do you leverage an Angularjs Factory/Service to use prototypical inheritance rather than constructor logic suggested by the service? 那么我的问题是如何利用Angularjs Factory / 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? 我不了解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. 但是,这与angularjs无关。这只是您以干净的方式实现原型继承的方式。

Your example should do nothing btw, because you dont return anything from the service. 顺便说一句,您的示例应该什么也不做,因为您不会从服务中返回任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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