获取对象或类的名称

是否有任何解决方案来获得一个对象的函数名?

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 in this) {...} -没有关于classNameObjectName的信息。有可能弄到一个吗?

409147 次浏览

获取对象的构造函数函数,然后检查它的的名字属性。

myObj.constructor.name

返回“myClass”。

例子:

function Foo () { console.log('Foo function'); }
var f = new Foo();
console.log('f', f.constructor.name); // -> "Foo"


var Bar = function () { console.log('Anonymous function (as Bar)'); };
var b = new Bar();
console.log('b', b.constructor.name); // -> "Bar"


var Abc = function Xyz() { console.log('Xyz function (as Abc)'); };
var a = new Abc();
console.log('a', a.constructor.name); // -> "Xyz"


class Clazz { constructor() { console.log('Clazz class'); } }
var c = new Clazz();
console.log('c', c.constructor.name); // -> "Clazz"


var otherClass = class Cla2 { constructor() { console.log('Cla2 class (as otherClass)'); } }
var c2 = new otherClass();
console.log('c2', c2.constructor.name); // -> "Cla2"

如果你使用标准的IIFE(例如TypeScript)

var Zamboch;
(function (_Zamboch) {
(function (Web) {
(function (Common) {
var App = (function () {
function App() {
}
App.prototype.hello = function () {
console.log('Hello App');
};
return App;
})();
Common.App = App;
})(Web.Common || (Web.Common = {}));
var Common = Web.Common;
})(_Zamboch.Web || (_Zamboch.Web = {}));
var Web = _Zamboch.Web;
})(Zamboch || (Zamboch = {}));

您可以在原型之前注释

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

JsFiddle

试试这个:

var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];
我也遇到过类似的困难,这里提供的解决方案都不是我所从事的工作的最佳解决方案。我所拥有的是一系列的函数,以模态显示内容,我试图在一个单一的对象定义下重构它,使类的函数和方法。 当我发现其中一个方法在模态内部创建了一些导航按钮,使用onClick到其中一个函数时,问题就出现了——现在是类的对象。我已经考虑过(并且仍在考虑)其他方法来处理这些导航按钮,但我能够通过在父窗口中定义的变量来找到类本身的变量名。 我所做的是搜索任何匹配'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。或者你应该问问自己“我为什么要这样做?”这真的是我要解决的问题吗?" < / 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));

结果:

enter image description here

代码:https://jsbin.com/wikiji/edit?js,console

我们需要的是:

  1. 在函数中封装一个常量(函数的名称等于我们想要获取的对象的名称)
  2. 在对象中使用箭头函数

console.clear();
function App(){ // name of my constant is App
return {
a: {
b: {
c: ()=>{ // very important here, use arrow function
console.log(this.constructor.name)
}
}
}
}
}
const obj = new App(); // usage


obj.a.b.c(); // App


// usage with react props etc,
// For instance, we want to pass this callback to some component


const myComponent = {};
myComponent.customProps = obj.a.b.c;
myComponent.customProps(); // App

在运行时获得类名的最有效方法

let className = this.constructor.name