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

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


当前回答

对于ES6中的Javascript类,您可以使用object.constructor。在下面的示例类中,getClass()方法返回你所期望的ES6类:

var Cat = class {

    meow() {

        console.log("meow!");

    }

    getClass() {

        return this.constructor;

    }

}

var fluffy = new Cat();

...

var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();

ruffles.meow();    // "meow!"

如果你从getClass方法实例化类,请确保将其括在括号中,例如ruffles = new (fluffy.getClass())(args…);

其他回答

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上都有不同的构造函数实例,因此在它们的构造函数上进行对象比较是行不通的。

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; 
   }   
}

在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。

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

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

function MyObject(){
}

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

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

obj instanceof MyObject // true