且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 10:46:04

如果你不能使用 myFunction.name 然后你可以:

If you can't use myFunction.name then you can:

// 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];
};

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

Or for modern browsers that don't support the name property (do they exist?) add it directly:

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