javascript获取类型/实例名称 [英] javascript get type/instance name

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

问题描述

是否有可靠的方法来获取JavaScript对象的实例?

Is there a reliable way of getting the instance of a JavaScript object?

例如,依赖假的' obj.getInstance( )'function。

For example, relying on the fake 'obj.getInstance()' function.

var T = {
    Q: {
        W: {
           C: function() {}
        }
    } 
};

var x = new T.Q.W.C();
console.log( x.getInstance() === T.Q.W.C); // should output true

如果这不是ECMA规范的一部分,请包含浏览器/节点。 js对答案的支持和兼容性。

If this is not part of the ECMA specification, please include browser/node.js support and compatibility in answers.

推荐答案

获取指向实例化函数的指针(不是类 ,但是类型),使用 obj.constructor 其中 obj 是任何对象。

To get a pointer to the instantiating function (which is not a "class", but is the type), use obj.constructor where obj is any object.

在JavaScript中没有类。因此,JavaScript中没有类实例。只有对象。对象继承自其他对象(它们所谓的原型)。你在代码中做的是字面上定义一个对象T,它的属性Q是另一个对象,其属性W是另一个对象,其属性C是一个函数。

In JavaScript there are no classes. As such, there are no class instances in JavaScript. There are only objects. Objects inherit from other objects (their so called prototypes). What you are doing in your code is literally defining an object T, which's attribute Q is another object, which's attribute W is another object, which's attribute C is a function.

当您创建TQWC的新实例时,实际上只是将函数TQWC称为构造函数。一个名为构造函数的函数将返回一个新对象,在该对象上调用构造函数(即这个为新对象,如 constructorFunction。 apply(newObject,arguments); )。返回的对象将具有隐藏属性构造函数,它将指向作为构造函数调用的函数来创建对象。此外,还有一个语言功能,允许您使用 instanceof 运算符测试给定函数是否用作对象的构造函数。

When you are "creating a new instance of T.Q.W.C", you are actually only calling the function T.Q.W.C as a constructor. A function called as a constructor will return a new object on which the constructor function was called (that is with this beeing the new object, like constructorFunction.apply(newObject, arguments);). That returned object will have a hidden property constructor which will point to the function that was invoked as a constrcutor to create the object. Additionally there is a language feature which allows you to test if a given function was used as the constructor function for an object using the instanceof operator.

所以你可以做以下事情:

So you could do the following:

console.log(x instanceof T.Q.W.C);

OR

console.log(x.constructor === T.Q.W.C);

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

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