确定 JavaScript 对象实例的类的名称 [英] Determine name of a JavaScript object instance's class

查看:45
本文介绍了确定 JavaScript 对象实例的类的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一个 JavaScript类"Foo:

Imagine a JavaScript "class" Foo:

var Foo = function()
{
};

还有那个类的一个实例:

And an instance of that class:

var foo = new Foo();

我可以直接从实例foo获取字符串Foo,还是Foo只是一个不能与实例关联的传递变量foo 实例化后?

Can I obtain the string Foo directly from the instance foo, or is Foo just a transitive variable that cannot be associated with the instance foo after instantiation?

EDIT 1 SLaks 建议使用 foo.constructor.这给出:

function ()
{
}

如果函数定义为以下形式,则此方法有效:

This approach works if the function is defined in the form:

function Foo()
{}

...但情况可能并非总是如此.

...but this might not always be the case.

EDIT 2 尝试 skizeey 的方法 也不起作用.它本质上是比 Slack 的方法更完整的尝试,但会产生一个空字符串:""

EDIT 2 Trying skizeey's approach doesn't work either. It is essentially a more complete attempt as Slack's method, but yields an empty string: ""

EDIT 3 我想知道这是否真的可行.请注意以下来自 Chrome 的 JavaScript 控制台的记录:

EDIT 3 I wonder whether this is actually possible somehow. Notice the following transcript from Chrome's JavaScript console:

> var Foo = function() {}
undefined
> var foo = new Foo();
undefined
> foo
Foo

在最后一行中,Chrome 清楚地知道该对象的类型为 Foo.然而,这可能只是 Chrome 的事情,而不是标准的 JavaScript,甚至无法从语言本身访问.

In the last line, Chrome clearly knows that the object is of type Foo. However this may just be a Chrome thing, and not standard JavaScript or even inaccessible from the language itself.

推荐答案

带命名函数:

> var Foo = function Foo(){};
> undefined
> var foo = new Foo();
> undefined
> foo.constructor.name
> "Foo"

未命名函数:

> var Foo = function (){};
> undefined
> var foo = new Foo();
> undefined
> foo.constructor.name
> ""

这篇关于确定 JavaScript 对象实例的类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆