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

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


当前回答

不要使用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;

其他回答

我现在有一个通用的情况,使用这个:

class Test {
  // your class definition
}

nameByType = function(type){
  return type.prototype["constructor"]["name"];
};

console.log(nameByType(Test));

这是我发现的唯一方法,以获得类名类型输入,如果你没有一个对象的实例。

(用ES2017编写)

点表示法也可以

console.log(Test.prototype.constructor.name); // returns "Test" 

如果你可以访问类Foo的实例(Foo = new Foo()),那么只有一种方法可以从实例中访问类:Foo。Javascript中的构造函数= Java中的foo.getClass()。

eval()是另一种方法,但由于eval()永远不被推荐,它适用于所有事情(类似于Java反射),所以不推荐使用这种方法。foo。构造函数= Foo

你也可以这样做

Hello { 构造函数(){ } } 函数isClass (func) { 返回typeof func === 'function' && /^class\s/.test(function .prototype. tostring .call(func)) } console.log (isClass(你好))

这将告诉您输入是否是类

我们可以通过执行'instance.constructor.name'来读取实例的Class名,如下例所示:

class Person {
  type = "developer";
}
let p = new Person();

p.constructor.name // Person

下面是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;
}