Angularjs Services,Factories和Prototypical inheritance

时间:2014-06-17 17:52:41

标签: javascript angularjs prototypal-inheritance

从我所阅读和测试过的内容中,尽可能避免构造函数和利用原型继承具有优势。它的速度更快(不是很多,但我必须循环使用+ 100,000个项目),允许更多的灵活性,并且更加原生于JavaScript的理念。

我的问题是你如何利用Angularjs Factory / Service来使用原型继承而不是服务建议的构造函数逻辑?

以下是我的例子:

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));
    });
});

如何更改服务或工厂以创建使用原型继承继承所有功能的项目?而且因为技术上更快(我不太了解)&更多原生的体验,为什么它不是标准的?我不了解Angularjs的一些内容吗?

1 个答案:

答案 0 :(得分:1)

而不是

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

你可以使用

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

   return Item;
})()

我认为这就是你的意思。这与angularjs无关。它只是你如何以干净的方式实现原型继承。

你的例子应该什么都不做,因为你不从服务中返回任何东西。

相关问题