分解多个函数

Factorise multiple functions

也许是愚蠢的问题但是:

如何分解这种代码?

  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);