我基于继承生成了一系列构造函数名称:
class Person {
}
class User extends Person {
}
$userClassIdentifier = generateIdentifier(User.constructor)
// userClassIdentifier = 'Person.User'
function generateIdentifier(constructor) {
if (constructor.prototype && constructor.prototype.__proto__
&& constructor.prototype.__proto__.constructor && constructor.prototype.__proto__.constructor.name) {
return `${constructor.prototype.__proto__.constructor.name}.${constructor.name}`
}
return constructor.name
}
这适用于一个级别的继承。但它似乎非常hacky /丑陋。有没有更好的方法来做到这一点,并使其适用于未知数量的深度?
答案 0 :(得分:3)
如果我有SUV扩展汽车延伸车辆,我期待'Vehicle.Car.SUV'
我会使用getPrototypeOf
和一个循环,从你想要开始的构造函数开始,并在构造函数的原型为Function.prototype
或null
时结束:
function getLineage(ctor) {
let name = ctor.name;
while ((ctor = Object.getPrototypeOf(ctor)) != Function.prototype && ctor) {
name = ctor.name + "." + name;
}
return name;
}
class Vehicle { }
class Car extends Vehicle { }
class SUV extends Car { }
console.log(getLineage(SUV));
我要做的一个建议是使用不同的分隔符而不是.
,因为.
似乎表明(比方说)SUV
是Car
的属性{1}},当然不是。 : - )