【问题标题】:Angularjs Services, Factories, and Prototypical inheritanceAngularjs 服务、工厂和原型继承
【发布时间】:2014-06-17 17:52:41
【问题描述】:

根据我的阅读和测试,避免构造函数并尽可能利用原型继承是有好处的。它更快(不是很多,但我必须遍历 +100,000 个项目),允许更大的灵活性,并且更符合 JavaScript 的理念。

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

这是我的例子:

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 不了解吗?

【问题讨论】:

标签: javascript angularjs prototypal-inheritance


【解决方案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 无关。它只是您如何以干净的方式实现原型继承。

顺便说一句,您的示例应该什么都不做,因为您不会从服务返回任何内容。

【讨论】:

  • 我不认为 IEFE 是必要的,Angular 的 service 回调隐含地做到了这一点
  • @Bergi:没必要。它只是我喜欢的风格。
  • 另外,我不会说原型继承一​​定更快......它只是使用更少的内存。如果你有一个 Singleton 什么的,就没有必要使用原型继承..
猜你喜欢
  • 1970-01-01
  • 2014-07-10
  • 2023-03-08
  • 2017-01-30
  • 2013-04-20
  • 2013-05-20
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多