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

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


当前回答

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

其他回答

对于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…);

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

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

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