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

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


当前回答

问题似乎已经回答了,但OP想要访问和对象的类,就像我们在Java中所做的那样,选择的答案是不够的(imho)。

通过下面的解释,我们可以得到一个对象的类(实际上在javascript中称为prototype)。

var arr = new Array('red', 'green', 'blue');
var arr2 = new Array('white', 'black', 'orange');

你可以像这样添加属性:

Object.defineProperty(arr,'last', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue

但是.last属性将只对从Array原型实例化的'arr'对象可用。因此,为了使.last属性对所有从Array prototype实例化的对象可用,我们必须为Array prototype定义.last属性:

Object.defineProperty(Array.prototype,'last', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue
console.log(arr2.last) // orange

这里的问题是,你必须知道“arr”和“arr2”变量属于哪种对象类型(原型)!换句话说,如果您不知道'arr'对象的类类型(原型),那么您将无法为它们定义属性。在上面的例子中,我们知道arr是Array对象的实例,这就是为什么我们使用Array。prototype为Array定义一个属性。但如果我们不知道“arr”的类(原型)呢?

Object.defineProperty(arr.__proto__,'last2', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue
console.log(arr2.last) // orange

正如你所看到的,在不知道'arr'是一个数组的情况下,我们可以添加一个新属性,只需使用'arr.__proto__'引用'arr'的类即可。

我们访问了'arr'的原型,但不知道它是Array的实例,我认为这是OP要求的。

其他回答

你也可以这样做

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

这将告诉您输入是否是类

我建议使用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'

如果你可以访问类Foo的实例(Foo = new Foo()),那么只有一种方法可以从实例中访问类:Foo。Javascript中的构造函数= Java中的foo.getClass()。

eval()是另一种方法,但由于eval()永远不被推荐,它适用于所有事情(类似于Java反射),所以不推荐使用这种方法。foo。构造函数= Foo

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

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