如果我想要一个用于创建多个“小部件”的Angular JS工厂,这是最好的方法吗?
从这个基本框架开始......
angular
.module('app')
.factory('widgetFactory', widgetFactory);
function widgetFactory() {
/* { Option A or B goes here } */
}
......似乎有两个大致相同的选项:
A - 返回带有创建功能的对象
return {
createWidget: createWidget
};
function createwidget(options) {
return new Widget(options);
}
function Widget (options) { // the class
this.name = options.name;
/* etc. */
}
然后在控制器中使用它,例如:var w = widgetFactory.createWidget(options);
...或... B - 返回一个函数(充当一个类)
return Widget;
function Widget (options) { // the class
this.name = options.name;
/* etc. */
}
然后在控制器中使用它,例如:var w = new widgetFactory(options);
Style guides like this one似乎指出“A”是首选,但并不完全清楚。