获取对象或类的名称

2020/10/15 02:21 · javascript ·  · 0评论

有什么解决方案来获取对象的函数名称?

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) {...}-没有有关className或的信息ObjectName有可能得到其中之一吗?

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

myObj.constructor.name

返回“ myClass”。

例:

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"

如果使用标准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

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

笔记:

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

结果:

在此处输入图片说明

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

我面临着类似的困难,这里介绍的解决方案都不是我正在研究的最佳解决方案。我所拥有的是一系列以模态形式显示内容的函数,我试图在单个对象定义下重构它,以使类成为函数,方法。当我发现其中一种方法自己在模态内部创建了一些导航按钮时,问题就来了,它们对函数之一使用了onClick-现在是类的一个对象。我已经考虑(并且仍在考虑)其他方法来处理这些导航按钮,但是我能够通过清除父窗口中定义的变量来为类本身找到变量名。我所做的就是搜索与我的班级“实例”相匹配的任何东西,如果可能不止一个,

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

尝试这个:

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

我们所需要的:

  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
本文地址:http://javascript.askforanswer.com/huoquduixianghuoleidemingcheng.html
文章标签:
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!