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

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


当前回答

为了保持ECMAScript 6一贯的向后兼容性,JavaScript仍然没有类类型(尽管不是每个人都理解这一点)。它确实有一个class关键字作为创建原型的类语法的一部分——但仍然没有称为class的东西。JavaScript现在不是,也从来都不是经典的OOP语言。从类的角度来谈论JS要么是一种误导,要么是一种还没有找到原型继承的迹象(只是保持它的真实)。

这意味着。构造函数仍然是获取构造函数引用的好方法。这个。constructor。prototype是访问原型本身的方法。因为这不是Java,所以它不是一个类。它是实例实例化的原型对象。下面是一个使用ES6语法糖创建原型链的例子:

class Foo {
  get foo () {
    console.info(this.constructor, this.constructor.name)
    return 'foo'
  }
}

class Bar extends Foo {
  get foo () {
    console.info('[THIS]', this.constructor, this.constructor.name, Object.getOwnPropertyNames(this.constructor.prototype))
    console.info('[SUPER]', super.constructor, super.constructor.name, Object.getOwnPropertyNames(super.constructor.prototype))

    return `${super.foo} + bar`
  }
}

const bar = new Bar()
console.dir(bar.foo)

这是使用babel-node输出的结果:

> $ babel-node ./foo.js                                                                                                                   ⬡ 6.2.0 [±master ●]
[THIS] [Function: Bar] 'Bar' [ 'constructor', 'foo' ]
[SUPER] [Function: Foo] 'Foo' [ 'constructor', 'foo' ]
[Function: Bar] 'Bar'
'foo + bar'

你知道了!2016年,JavaScript中有class关键字,但仍然没有类类型。这一点。构造函数是获取构造函数的最佳方式,this。Constructor。prototype是访问原型本身的最佳方式。

其他回答

这个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...

不要使用o.constructor,因为它可以被对象内容改变。相反,使用Object.getPrototypeOf()?.constructor。

const fakedArray = JSON.parse('{ "constructor": { "name": "Array" } }');

// returns 'Array', which is faked.
fakedArray.constructor.name;

// returns 'Object' as expected
Object.getPrototypeOf(fakedArray)?.constructor?.name;

我建议使用Object.prototype.constructor.name:

Object.defineProperty(Object.prototype, "getClass", {
    value: function() {
      return this.constructor.name;
    }
});

var x = new DOMParser();
console.log(x.getClass()); // `DOMParser'

var y = new Error("");
console.log(y.getClass()); // `Error'

在javascript中,没有类,但我认为您需要构造函数名称和obj.constructor.toString()将告诉您需要什么。

getClass()函数使用constructor.prototype.name

我找到了一种方法来访问类,比上面的一些解决方案要干净得多;在这儿。

function getClass(obj) {

   // if the type is not an object return the type
   if((let type = typeof obj) !== 'object') return type; 
    
   //otherwise, access the class using obj.constructor.name
   else return obj.constructor.name;   
}

它是如何工作的

构造函数有一个名为name access的属性,它将为您提供类名。

更简洁的代码版本:

function getClass(obj) {

   // if the type is not an object return the type
   let type = typeof obj
   if((type !== 'object')) { 
      return type; 
   } else { //otherwise, access the class using obj.constructor.name
      return obj.constructor.name; 
   }   
}