我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
当前回答
我现在有一个通用的情况,使用这个:
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"
其他回答
我建议使用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'
Javascript是一种无类语言:它不像Java那样有静态定义类行为的类。JavaScript使用原型而不是类来定义对象属性,包括方法和继承。用JavaScript中的原型模拟许多基于类的特性是可能的。
对于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;
}
如果你不仅需要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'