检索在函数内声明的闭包的名称

时间:2014-06-04 14:16:25

标签: javascript reflection closures nested-function

如果我们有:

function parent(){

  function a(){
     return 'i am a';
  }
  function b(){
      return 'i am b';
  }
  function c(e,f){
      console.log(e+f);
  }
  c(a(),b());
}

任何检索嵌套函数名称的内置方法:a,b,c。让我们说:

 parent.closures()
 // ['a','b','c']

}

1 个答案:

答案 0 :(得分:0)

DEMO

Function.prototype.closures=function() { 
    var that=this,fn = function(r) {
         //see demo==> to reduce non-functional code
    };
    return this.toString().split("\n").filter(function(d) {
        return d.indexOf('function ') !== -1
    }).map(fn).filter(function(f) {
        return f !== that.name;
    })
};

然后:

 parent.closures()
 // ['a','b','c']