获取对象或类的名称

时间:2021-03-06 16:45:13

Is there any solution to get the function name of an object?

有什么方法可以得到对象的函数名?

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) {...} - there is no information about the className or ObjectName. Is it possible to get one of them?

for (var k in this){…} -没有关于类名或ObjectName的信息。有可能买一个吗?

6 个解决方案

#1


219  

Get your object's constructor function and then inspect its name property.

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

myObj.constructor.name

Returns "myClass".

返回“myClass”。

#2


17  

Example:

例子:

function Foo () { console.log('Foo function'); }
var Bar = function () { console.log('Bar function'); };
var Abc = function Xyz() { console.log('Abc function'); };

var f = new Foo();
var b = new Bar();
var a = new Abc();

console.log('f', f.constructor.name); // -> "Foo"
console.log('b', b.constructor.name); // -> "Function"
console.log('a', a.constructor.name); // -> "Xyz"

#3


5  

If you use standard IIFE (for example with TypeScript)

如果您使用标准的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 = {}));

you could annotate the prototypes upfront with

您可以预先注释原型

setupReflection(Zamboch, 'Zamboch', 'Zamboch');

and then use _fullname and _classname fields.

然后使用_fullname和_classname字段。

var app=new Zamboch.Web.Common.App();
console.log(app._fullname);

annotating function here:

注释功能:

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

JsFiddle

#4


4  

Try this:

试试这个:

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

#5


4  

As this was already answered, I just wanted to point out the differences in approaches on getting the constructor of an object in JavaScript. There is a difference between the constructor and the actual object/class name. If the following adds to the complexity of your decision then maybe you're looking for instanceof. Or maybe you should ask yourself "Why am I doing this? Is this really what I am trying to solve?"

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

Notes:

注:

The obj.constructor.name is not available on older browsers. Matching (\w+) should satisfy ES6 style classes.

在旧的浏览器上不能使用object .construct .name。匹配(\w+)应该满足ES6样式类。

Code:

代码:

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

Result:

结果:

获取对象或类的名称

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

代码:https://jsbin.com/wikiji/edit?js,控制台

#6


2  

I was facing a similar difficulty and none of the solutions presented here were optimal for what I was working on. What I had was a series of functions to display content in a modal and I was trying to refactor it under a single object definition making the functions, methods of the class. The problem came in when I found one of the methods created some nav-buttons inside the modal themselves which used an onClick to one of the functions -- now an object of the class. I have considered (and am still considering) other methods to handle these nav buttons, but I was able to find the variable name for the class itself by sweeping the variables defined in the parent window. What I did was search for anything matching the 'instanceof' my class, and in case there might be more than one, I compared a specific property that was likely to be unique to each instance:

我也遇到了类似的困难,这里提供的解决方案都不是我正在做的事情的最佳方案。我有一系列的函数以模态形式显示内容,我试图在一个对象定义下重构它生成类的函数和方法。当我发现其中一个方法在模式本身中创建了一些导航按钮时,问题就出现了,它使用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;
    }
}

#1


219  

Get your object's constructor function and then inspect its name property.

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

myObj.constructor.name

Returns "myClass".

返回“myClass”。

#2


17  

Example:

例子:

function Foo () { console.log('Foo function'); }
var Bar = function () { console.log('Bar function'); };
var Abc = function Xyz() { console.log('Abc function'); };

var f = new Foo();
var b = new Bar();
var a = new Abc();

console.log('f', f.constructor.name); // -> "Foo"
console.log('b', b.constructor.name); // -> "Function"
console.log('a', a.constructor.name); // -> "Xyz"

#3


5  

If you use standard IIFE (for example with TypeScript)

如果您使用标准的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 = {}));

you could annotate the prototypes upfront with

您可以预先注释原型

setupReflection(Zamboch, 'Zamboch', 'Zamboch');

and then use _fullname and _classname fields.

然后使用_fullname和_classname字段。

var app=new Zamboch.Web.Common.App();
console.log(app._fullname);

annotating function here:

注释功能:

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

JsFiddle

#4


4  

Try this:

试试这个:

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

#5


4  

As this was already answered, I just wanted to point out the differences in approaches on getting the constructor of an object in JavaScript. There is a difference between the constructor and the actual object/class name. If the following adds to the complexity of your decision then maybe you're looking for instanceof. Or maybe you should ask yourself "Why am I doing this? Is this really what I am trying to solve?"

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

Notes:

注:

The obj.constructor.name is not available on older browsers. Matching (\w+) should satisfy ES6 style classes.

在旧的浏览器上不能使用object .construct .name。匹配(\w+)应该满足ES6样式类。

Code:

代码:

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

Result:

结果:

获取对象或类的名称

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

代码:https://jsbin.com/wikiji/edit?js,控制台

#6


2  

I was facing a similar difficulty and none of the solutions presented here were optimal for what I was working on. What I had was a series of functions to display content in a modal and I was trying to refactor it under a single object definition making the functions, methods of the class. The problem came in when I found one of the methods created some nav-buttons inside the modal themselves which used an onClick to one of the functions -- now an object of the class. I have considered (and am still considering) other methods to handle these nav buttons, but I was able to find the variable name for the class itself by sweeping the variables defined in the parent window. What I did was search for anything matching the 'instanceof' my class, and in case there might be more than one, I compared a specific property that was likely to be unique to each instance:

我也遇到了类似的困难,这里提供的解决方案都不是我正在做的事情的最佳方案。我有一系列的函数以模态形式显示内容,我试图在一个对象定义下重构它生成类的函数和方法。当我发现其中一个方法在模式本身中创建了一些导航按钮时,问题就出现了,它使用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;
    }
}