jjzjj

javascript - AngularJS 设计模式 : Should I use factories to create constructor functions?

coder 2024-05-09 原文

这是我在创建 AngularJS 应用程序时一直在考虑的问题。当我第一次了解 AngularJS 工厂时,我认为它们的一个巧妙用法是创建并返回一个构造函数而不是一个普通对象,例如:

app.factory("Foo", function() {
  function Foo(bar, baz) {
    this.bar = bar;
    this.baz = baz;
    ...
  }

  Foo.prototype = {
    constructor: Foo,
    method1: function() { ... },
    method2: function() { ... },
    ...,
    methodn: function() { ... },
  };

  return Foo;
});

然后,您可以将该函数注入(inject)您的 Controller 并使用 new 调用它。我发现这在美学上令人愉悦且符合 OOP-y,但现在我开始认为它实际上是一种反模式。问题是当你在 AngularJS 感知的上下文中工作时它工作得很好,但是一旦你想,例如,从控制台调用构造函数,在 Web Worker 中使用它,或者在非 - AngularJS 应用程序,您开始必须围绕 AngularJS 而不是使用它。我开始怀疑这种方法是否被误导了,因为 javascript 中的函数似乎已经是“单例”并且似乎不需要任何实例化帮助。

我是否滥用了 AngularJS 工厂?使用暴露于全局范围的构造函数会更好吗?更一般地说,是否有特定因素促进 AngularJS 工厂/服务/提供者在全局对象上的使用,反之亦然?

最佳答案

是的!

Factories Syntax: module.factory( 'factoryName', function ); Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory. Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

来源:https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/HuZsOsMvKv4J

以上链接也用作Bart's 的来源。评论:AngularJS: Service vs provider vs factory

关于javascript - AngularJS 设计模式 : Should I use factories to create constructor functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18072683/

有关javascript - AngularJS 设计模式 : Should I use factories to create constructor functions?的更多相关文章

随机推荐