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

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


当前回答

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

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

p.constructor.name // Person

其他回答

在JavaScript中没有与Java的getClass()完全对应的方法。这主要是因为JavaScript是基于原型的语言,而Java是基于类的语言。

根据你需要getClass()做什么,JavaScript中有几个选项:

typeof 运算符 obj.constructor 函数。原型,proto.isPrototypeOf

举几个例子:

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

typeof Foo;             // == "function"
typeof foo;             // == "object"

foo instanceof Foo;     // == true
foo.constructor.name;   // == "Foo"
Foo.name                // == "Foo"    

Foo.prototype.isPrototypeOf(foo);   // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21);            // == 42

注意:如果你用Uglify编译你的代码,它会改变非全局类名。为了防止这种情况,Uglify有一个——mangle参数,你可以使用gulp或grunt将其设置为false。

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

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" 

如果你不仅需要GET类,还需要EXTEND类,这样写:

让我们来

 class A{ 
   constructor(name){ 
     this.name = name
   }
 };

 const a1 = new A('hello a1');

因此扩展A只使用实例:

const a2 = new (Object.getPrototypeOf(a1)).constructor('hello from a2')
// the analog of const a2 = new A()

console.log(a2.name)//'hello from a2'

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

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

p.constructor.name // Person

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