分解多个功能

Factorise multiple functions

本文关键字:功能 分解      更新时间:2023-09-26

也许是愚蠢的问题,但是:

如何分解此类代码?

  var rsc = this.checkRsc(path)
  if (rsc)

基本上,我想在使用任何方法之前检查事物是否为空。

checkRsc: function(path) {
  var rsc = manager.get(path);
  if (rsc != undefined)
    return rsc;
  else
    return null;
},
func1: function(path) {
  var rsc = this.checkRsc(path)
  if (rsc)
    this.doStuff(rsc);
},
func2: function(path) {
  var rsc = this.checkRsc(path)
  if (rsc)
    this.doStuffAnotherStuff(rsc);
},
func3: function(path) {
  var wave = this.checkRsc(path)
  if (wave)
    this.andAgain(wave);
},
func4: function(path) {
  var rsc = this.checkRsc(path)
  if (rsc)
    this.AndsomethingElse(rsc);
}

传递要执行的函数,如下所示

checkRsc: function(path, func, context) {
  var rsc = manager.get(path);
  if (rsc != undefined)
    return func.call(context, rsc);
  else
    return null;
},

然后像这样调用它

this.checkRsc(path, this.doStuff, this)
...
this.checkRsc(path, this.doStuffAnotherStuff, this)
...
this.checkRsc(path, this.andAgain, this)

注意:我也建议传递上下文,因为如果您想在嵌套对象中执行函数,这将派上用场。例如

this.checkRsc(path, this.nested.again, this.nested)

现在

    return func.call(context, rsc);

将像这样工作

    return [this.nested.again func obj (without context)].call(this.nested, rsc);