我创建了一个JavaScript对象,但如何确定该对象的类?

我想要类似于Java的. getclass()方法的东西。


当前回答

下面是getClass()和getInstance()的实现

你可以使用this.constructor获取Object类的引用。

从实例上下文:

function A() {
  this.getClass = function() {
    return this.constructor;
  }

  this.getNewInstance = function() {
    return new this.constructor;
  }
}

var a = new A();
console.log(a.getClass());  //  function A { // etc... }

// you can even:
var b = new (a.getClass());
console.log(b instanceof A); // true
var c = a.getNewInstance();
console.log(c instanceof A); // true

来自静态上下文:

function A() {};

A.getClass = function() {
  return this;
}

A.getInstance() {
  return new this;
}

其他回答

你可以通过使用constructor属性获取创建对象的构造函数的引用:

function MyObject(){
}

var obj = new MyObject();
obj.constructor; // MyObject

如果你需要在运行时确认对象的类型,你可以使用instanceof操作符:

obj instanceof MyObject // true

我发现object.constructor. tostring()在IE中返回[object objectClass],而不是在chome中返回函数objectClass(){}。所以,我认为http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects中的代码在IE中可能不能很好地工作。我修复了代码如下:

代码:

var getObjectClass = function (obj) {
        if (obj && obj.constructor && obj.constructor.toString()) {
            
                /*
                 *  for browsers which have name property in the constructor
                 *  of the object,such as chrome 
                 */
                if(obj.constructor.name) {
                    return obj.constructor.name;
                }
                var str = obj.constructor.toString();
                /*
                 * executed if the return of object.constructor.toString() is 
                 * "[object objectClass]"
                 */
                 
                if(str.charAt(0) == '[')
                {
                        var arr = str.match(/\[\w+\s*(\w+)\]/);
                } else {
                        /*
                         * executed if the return of object.constructor.toString() is 
                         * "function objectClass () {}"
                         * for IE Firefox
                         */
                        var arr = str.match(/function\s*(\w+)/);
                }
                if (arr && arr.length == 2) {
                            return arr[1];
                        }
          }
          return undefined; 
    };
    

Javascript是一种无类语言:它不像Java那样有静态定义类行为的类。JavaScript使用原型而不是类来定义对象属性,包括方法和继承。用JavaScript中的原型模拟许多基于类的特性是可能的。

obj.constructor.name

是现代浏览器中的可靠方法。Function.name在ES6中被正式添加到标准中,使其成为一种标准兼容的方法,以字符串的形式获取JavaScript对象的“类”。如果用var obj = new MyClass()实例化对象,它将返回"MyClass"。

它将为数字返回“Number”,为数组返回“Array”,为函数返回“Function”等等。它通常会像预期的那样运行。唯一失败的情况是通过object创建的对象没有原型。Create (null),或者从匿名定义(未命名)函数实例化对象。

还要注意,如果您正在缩小代码,那么与硬编码的类型字符串进行比较是不安全的。例如,不是检查obj.constructor.name == "MyType",而是检查obj.constructor.name == MyType.name。或者只是比较构造函数本身,但这不能跨DOM边界工作,因为每个DOM上都有不同的构造函数实例,因此在它们的构造函数上进行对象比较是行不通的。

这个getNativeClass()函数对于未定义的值返回“undefined”,对于空值返回“null”。对于所有其他值,CLASSNAME-part从[object CLASSNAME]中提取,这是使用object .prototype. tostring .call(value)的结果。

getAnyClass()的行为与gettnativeclass()相同,但也支持自定义构造函数

function getNativeClass(obj) {
  if (typeof obj === "undefined") return "undefined";
  if (obj === null) return "null";
  return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
}

function getAnyClass(obj) {
  if (typeof obj === "undefined") return "undefined";
  if (obj === null) return "null";
  return obj.constructor.name;
}

getClass("")   === "String";
getClass(true) === "Boolean";
getClass(0)    === "Number";
getClass([])   === "Array";
getClass({})   === "Object";
getClass(null) === "null";

getAnyClass(new (function Foo(){})) === "Foo";
getAnyClass(new class Foo{}) === "Foo";

// etc...