该问题有多种解决方案,具体取决于您的应用程序有多大。您提到的两个解决方案是最明显的解决方案。我宁愿选择基于重新构建代码的第三个。我提供的解决方案看起来很像执行者模式。
首先创建需要这种特定形式的通用模块的操作 -
var Action_One = function(commonItems) {
this.commonItems = commonItems;
};
Action_One.prototype.execute = function() {
//..blah blah
//Your action specific code
};
var Action_Two = function(commonItems) {
this.commonItems = commonItems;
};
Action_Two.prototype.execute = function() {
//..blah blah
//Your action_two specific code
};
现在创建一个动作初始化器,它将像这样以编程方式初始化您的动作 -
var ActionInitializer = function(commonItems) {
this.commonItems = commonItems;
};
ActionInitializer.prototype.init = function(Action) {
var obj = new Action(this.commonItems);
return obj;
};
下一步是创建一个动作执行器 -
//You can create a more complex executor using `Async` lib or something else
var Executor = function(ActionInitializer, commonItems) {
this.initializer = new ActionInitializer(commonItems);
this.actions = [];
};
//Use this to add an action to the executor
Executor.prototype.add = function(action) {
var result = this.initializer.init(action);
this.actions.push(result);
};
//Executes all the actions
Executor.prototype.executeAll = function() {
var result = [];
for (var i = this.action.length - 1; i >= 0; i--) {
result[i] = this.action[i].execute();
}
this.action = []
return result;
};
想法是解耦每个模块,以便Executor
在这种情况下只有一个模块依赖于公共属性。现在让我们看看它是如何工作的——
var commonProperties = {a:1, b:2};
//Pass the action initilizer class and the common property object to just this one module
var e = new Executor(ActionInitializer, commonProperties);
e.add(Action_One);
e.add(Action_Two);
e.executeAll();
console.log(e.results);
这样,您的程序将更清洁且更具可扩展性。如果不清楚,请提出问题。快乐编码!