从Javascript函数引用中获取名称String?

Gil*_*ili 35 javascript

我想从其名称作为字符串执行Get JavaScript function-object的相反操作

那是,给定:

function foo()
{}

function bar(callback)
{
  var name = ???; // how to get "foo" from callback?
}

bar(foo);
Run Code Online (Sandbox Code Playgroud)

如何获取引用背后的函数名称?

Phr*_*ogz 29

如果你不能使用myFunction.name那么你可以:

// Add a new method available on all function values
Function.prototype.getName = function(){
  // Find zero or more non-paren chars after the function start
  return /function ([^(]*)/.exec( this+"" )[1];
};
Run Code Online (Sandbox Code Playgroud)

或者对于不支持该name属性的现代浏览器(它们是否存在?)直接添加它:

if (Function.prototype.name === undefined){
  // Add a custom property to all function values
  // that actually invokes a method to get the value
  Object.defineProperty(Function.prototype,'name',{
    get:function(){
      return /function ([^(]*)/.exec( this+"" )[1];
    }
  });
}
Run Code Online (Sandbox Code Playgroud)


gdo*_*ica 18

var name = callback.name;
Run Code Online (Sandbox Code Playgroud)

MDN:

name属性返回函数的名称,或匿名函数的空字符串:

请注意,这家酒店不是标准配置.

现场演示


koj*_*iro 6

function bar(callback){
    var name=callback.toString();
    var reg=/function ([^\(]*)/;
    return reg.exec(name)[1];
}

>>> function foo() { };
>>> bar(foo);
"foo"
>>> bar(function(){});
""
Run Code Online (Sandbox Code Playgroud)