我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
我创建了一个JavaScript对象,但如何确定该对象的类?
我想要类似于Java的. getclass()方法的东西。
当前回答
还有另一种技术可以识别类 你可以像下面这样在实例中存储引用到你的类。
class MyClass {
static myStaticProperty = 'default';
constructor() {
this.__class__ = new.target;
this.showStaticProperty = function() {
console.log(this.__class__.myStaticProperty);
}
}
}
class MyChildClass extends MyClass {
static myStaticProperty = 'custom';
}
let myClass = new MyClass();
let child = new MyChildClass();
myClass.showStaticProperty(); // default
child.showStaticProperty(); // custom
myClass.__class__ === MyClass; // true
child.__class__ === MyClass; // false
child.__class__ === MyChildClass; // true
其他回答
在javascript中,没有类,但我认为您需要构造函数名称和obj.constructor.toString()将告诉您需要什么。
我们可以通过执行'instance.constructor.name'来读取实例的Class名,如下例所示:
class Person {
type = "developer";
}
let p = new Person();
p.constructor.name // Person
这个getNativeClass()函数对于未定义的值返回“undefined”,对于空值返回“null”。对于所有其他值,CLASSNAME-part从[object CLASSNAME]中提取,这是使用object .prototype. tostring .call(value)的结果。
getAnyClass()的行为与gettnativeclass()相同,但也支持自定义构造函数
function getNativeClass(obj) {
if (typeof obj === "undefined") return "undefined";
if (obj === null) return "null";
return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
}
function getAnyClass(obj) {
if (typeof obj === "undefined") return "undefined";
if (obj === null) return "null";
return obj.constructor.name;
}
getClass("") === "String";
getClass(true) === "Boolean";
getClass(0) === "Number";
getClass([]) === "Array";
getClass({}) === "Object";
getClass(null) === "null";
getAnyClass(new (function Foo(){})) === "Foo";
getAnyClass(new class Foo{}) === "Foo";
// etc...
你可以通过使用constructor属性获取创建对象的构造函数的引用:
function MyObject(){
}
var obj = new MyObject();
obj.constructor; // MyObject
如果你需要在运行时确认对象的类型,你可以使用instanceof操作符:
obj instanceof MyObject // true
如果你不仅需要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'