Javascript 分解多个函数

Javascript 分解多个函数,javascript,refactoring,Javascript,Refactoring,也许是个愚蠢的问题,但是: 我如何分解这种代码 var rsc = this.checkRsc(path) if (rsc) 基本上,我想在使用任何方法之前检查一个东西是否为null checkRsc: function(path) { var rsc = manager.get(path); if (rsc != undefined) return rsc; else return null; }, func1: function(path) { va

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

我如何分解这种代码

  var rsc = this.checkRsc(path)
  if (rsc)
基本上,我想在使用任何方法之前检查一个东西是否为null

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)
    return [this.nested.again func obj (without context)].call(this.nested, 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)
    return [this.nested.again func obj (without context)].call(this.nested, rsc);

注意:我建议也传递上下文,因为如果您想在嵌套对象中执行函数,这会很方便。比如说,

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

我会像这样工作

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)
    return [this.nested.again func obj (without context)].call(this.nested, rsc);

if(rsc!=未定义)返回rsc;否则返回null
==>
返回src | nully嗯,我没有精确说明func1、fun2、func3等中的代码。。我想重构^^^将方法名传递给
func
,创建
rsc
,检查其存在性,并使用括号表示法调用该方法:
this[method\u name](rsc)需要时。这样你就只需要一个函数。好的函数也会检查这个