Javascript 获取对象或类的名称

Javascript 获取对象或类的名称,javascript,Javascript,有没有办法获取对象的函数名 function alertClassOrObject (o) { window.alert(o.objectName); //"myObj" OR "myClass" as a String } function myClass () { this.foo = function () { alertClassOrObject(this); } } var myObj = new myClass(); myObj.foo(); f

有没有办法获取对象的函数名

function alertClassOrObject (o) {
   window.alert(o.objectName); //"myObj" OR "myClass" as a String
}

function myClass () {
   this.foo = function () {
       alertClassOrObject(this);
   }
}

var myObj = new myClass();
myObj.foo();
for(此中的var k){…}
-没有关于
类名
对象名
的信息。有可能买一个吗

获取对象的函数,然后检查其属性

myObj.constructor.name
返回“myClass”。

示例:

function Foo(){console.log('Foo function');}
var f=新的Foo();
console.log('f',f.constructor.name);//->“福”
var Bar=function(){console.log('Anonymous function(as Bar);};
var b=新条();
console.log('b',b.constructor.name);//->“酒吧”
var Abc=函数Xyz(){console.log('Xyz函数(作为Abc);};
var a=新的Abc();
console.log('a',a.constructor.name);//->“Xyz”
类Clazz{constructor(){console.log('Clazz class');}
var c=新类别();
console.log('c',c.constructor.name);//->“咔嗒”
var otherClass=Cla2类{constructor(){console.log('Cla2类(作为otherClass);}
var c2=新的otherClass();
console.log('c2',c2.constructor.name);//->“Cla2”
如果您使用标准IIFE(例如与TypeScript一起使用)

您可以使用

setupReflection(Zamboch, 'Zamboch', 'Zamboch');
然后使用_fullname和_classname字段

var app=new Zamboch.Web.Common.App();
console.log(app._fullname);
此处的注释功能:

function setupReflection(ns, fullname, name) {
    // I have only classes and namespaces starting with capital letter
    if (name[0] >= 'A' && name[0] <= 'Z') {
        var type = typeof ns;
        if (type == 'object') {
            ns._refmark = ns._refmark || 0;
            ns._fullname = fullname;
            var keys = Object.keys(ns);
            if (keys.length != ns._refmark) {
                // set marker to avoid recusion, just in case 
                ns._refmark = keys.length;
                for (var nested in ns) {
                    var nestedvalue = ns[nested];
                    setupReflection(nestedvalue, fullname + '.' + nested, nested);
                }
            }
        } else if (type == 'function' && ns.prototype) {
            ns._fullname = fullname;
            ns._classname = name;
            ns.prototype._fullname = fullname;
            ns.prototype._classname = name;
        }
    }
}
试试这个:

var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];

我也面临着类似的困难,这里提出的解决方案中没有一个是最适合我工作的。我所拥有的是一系列以模态显示内容的函数,我试图在单个对象定义下对其进行重构,生成类的函数和方法。 当我发现其中一个方法在模态内部创建了一些导航按钮时,问题就出现了,它使用了一个函数的onClick——现在是类的对象。我已经考虑过(现在仍在考虑)处理这些nav按钮的其他方法,但是我能够通过扫描父窗口中定义的变量来找到类本身的变量名。 我所做的是搜索与我的类的“instanceof”匹配的任何内容,如果可能有多个,我会比较每个实例可能唯一的特定属性:

var myClass = function(varName)
{
    this.instanceName = ((varName != null) && (typeof(varName) == 'string') && (varName != '')) ? varName : null;

    /**
     * caching autosweep of window to try to find this instance's variable name
     **/
    this.getInstanceName = function() {
        if(this.instanceName == null)
        {
            for(z in window) {
                if((window[z] instanceof myClass) && (window[z].uniqueProperty === this.uniqueProperty)) {
                    this.instanceName = z;
                    break;
                }
            }
        }
        return this.instanceName;
    }
}

由于已经回答了这个问题,我只想指出在JavaScript中获取对象构造函数的方法的不同。 构造函数和实际对象/类名之间存在差异。如果以下情况增加了您决策的复杂性,那么您可能正在寻找
instanceof
。或者你应该问自己“我为什么要这样做?这真的是我想要解决的问题吗?”

注意事项:

var what = function(obj) {
  return obj.toString().match(/ (\w+)/)[1];
};

var p;

// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// ES6 class.
class NPC { 
  constructor() {
  }
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// ES6 class extended
class Boss extends NPC {
  constructor() {
    super();
  }
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
obj.constructor.name
在旧浏览器上不可用。 匹配的
(\w+)
应该满足ES6样式的类

代码:

var what = function(obj) {
  return obj.toString().match(/ (\w+)/)[1];
};

var p;

// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// ES6 class.
class NPC { 
  constructor() {
  }
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// ES6 class extended
class Boss extends NPC {
  constructor() {
    super();
  }
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
结果:

var what = function(obj) {
  return obj.toString().match(/ (\w+)/)[1];
};

var p;

// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));

// ES6 class.
class NPC { 
  constructor() {
  }
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

// ES6 class extended
class Boss extends NPC {
  constructor() {
    super();
  }
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));

代码:

我们需要的全部:

  • 在函数中包装一个常量(其中函数的名称等于我们要获取的对象的名称)
  • 在对象内部使用箭头函数
  • console.clear();
    函数App(){//我的常量的名称是App
    返回{
    a:{
    b:{
    c:()=>{//这里很重要,使用箭头函数
    console.log(this.constructor.name)
    }
    }
    }
    }
    }
    const obj=新应用程序();//使用
    obj.a.b.c();//应用程序
    //与react道具等配合使用,
    //例如,我们希望将此回调传递给某个组件
    常量myComponent={};
    myComponent.customProps=对象a.b.c;
    
    myComponent.customProps();//应用程序
    在运行时获取类名的最有效方法


    让className=this.constructor.name

    你可能想看看这个:当心!如果缩小JavaScript,构造函数的名称将更改。Handy,但还有一个警告:如果对象有一个原型链(除了
    对象
    ),您将获得该链中第一个链接的名称,而不是用于创建对象的构造函数的名称。以下面的例子:
    函数Daddy(){};函数Me(){};Me.prototype=新爸爸;我=新的我
    me.constructor.name
    然后意外返回
    'Daddy'
    ,而不是
    'me'
    。同样值得知道的是,name属性在var Foo=function(){>myclass=(function(){});新的myclass
    打印
    myclass{}
    在使用显示模块模式时,始终会显示“Object”<代码>函数Foo(){return{'Foo':'bar'};var f=新的Foo():(“b”日志现在输出FF88和节点中的“Bar”(通过)。似乎匿名函数现在继承了它们的变量名。如果您想知道的话,类使用与
    new
    @DerekWhite一起使用的类名。这是真的!更新后。有没有比obj.constructor.name更准确的情况?我只是看不出有任何原因导致这种复杂性。