![](/img/trans.png)
[英]Can I find the class name of a argument of the a function in javascript?
[英]How can I find the name of a JavaScript function
例如,我有一个名为“Apples()”的函数和一个名为“Pears()”的函数。 这些将通过各种调用来实例化,例如 new Apples() 或 new Pears()。 所有这些新实例都将存储在一个数组中。
稍后,我想通过数组扫描“Apples”的实例,但我无法找到如何识别我正在检索的对象。
我通过在每个适当的函数中声明 this.type = "Apples" 或 this.type = "Pears" 克服了这个困难,但这似乎是一个相当笨拙的解决方案,特别是因为 Google Chrome 调试器能够识别 Object 类型.
建议的解决方案
"var prot = Object.prototype.toString.call(arrayEntry(i))
产生 [object Object] - 不幸的是根本没有用。
这很好用:
您可以使用
Object.getPrototypeOf()
函数获取原型。 构造函数将在原型的构造函数属性中,您可以从 name 属性中获取其名称。
function getClassName(obj) {
return Object.getPrototypeOf(obj).constructor.name;
}
您可以使用Object.getPrototypeOf()
函数来获取原型。 构造函数将在原型的constructor
属性中,您可以从name
属性中获取其名称。
function getClassName(obj) { return Object.getPrototypeOf(obj).constructor.name; } function Apples() {} function Oranges() {} a = new Apples(); o = new Oranges(); console.log(getClassName(a)); console.log(getClassName(o));
这是您可以读取function
对象的name
成员的方式:
const test = () => console.log(test) console.log(test.name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.