我创建了一个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'

其他回答

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

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

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

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

p.constructor.name // Person

要获得“伪类”,可以通过获取构造函数

obj.constructor

假设在你进行继承时构造函数被正确地设置了——就像这样:

Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

这两行,加上:

var woofie = new Dog()

会做出伍菲。构造器指向狗。注意,Dog是一个构造函数,是一个function对象。但是你可以这样做,如果。构造函数=== Dog){…}。

如果你想获得类名作为字符串,我发现以下工作良好:

http://blog.magnetiq.com/post/514962277/finding-out-class-names-of-javascript-objects

function getObjectClass(obj) {
    if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return undefined;
}

它获取构造函数,将其转换为字符串,并提取构造函数的名称。

注意,obj.constructor.name可以很好地工作,但它不是标准的。它支持Chrome和Firefox,但不支持IE,包括IE 9或IE 10 RTM。

你也可以这样做

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

这将告诉您输入是否是类