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

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


当前回答

如果你不仅需要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'

其他回答

我发现object.constructor. tostring()在IE中返回[object objectClass],而不是在chome中返回函数objectClass(){}。所以,我认为http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects中的代码在IE中可能不能很好地工作。我修复了代码如下:

代码:

var getObjectClass = function (obj) {
        if (obj && obj.constructor && obj.constructor.toString()) {
            
                /*
                 *  for browsers which have name property in the constructor
                 *  of the object,such as chrome 
                 */
                if(obj.constructor.name) {
                    return obj.constructor.name;
                }
                var str = obj.constructor.toString();
                /*
                 * executed if the return of object.constructor.toString() is 
                 * "[object objectClass]"
                 */
                 
                if(str.charAt(0) == '[')
                {
                        var arr = str.match(/\[\w+\s*(\w+)\]/);
                } else {
                        /*
                         * executed if the return of object.constructor.toString() is 
                         * "function objectClass () {}"
                         * for IE Firefox
                         */
                        var arr = str.match(/function\s*(\w+)/);
                }
                if (arr && arr.length == 2) {
                            return arr[1];
                        }
          }
          return undefined; 
    };
    

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

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" 

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

function MyObject(){
}

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

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

obj instanceof MyObject // true

对于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那样有静态定义类行为的类。JavaScript使用原型而不是类来定义对象属性,包括方法和继承。用JavaScript中的原型模拟许多基于类的特性是可能的。