我想訪問創建物件的類的靜態成員,包括擴展建構式的父類。
我目前的作業是將每個類添加到建構式中的一個陣列中,但是,如果存在一個更優雅的解決方案,因為我正在定義數千個類,或者一種將 Type 限制為主類的方法。
這是一些示例代碼來說明我的意思。
type Class = { new(...args: any[]): any; }
class Animal {
static description = "A natural being that is not a person"
classes : Class[] = []
constructor() {
this.classes.push(Animal)
}
}
class Mammal extends Animal {
static description = "has live births and milk"
constructor() {
super() // adds Animal to classes
this.classes.push(Mammal)
}
}
class Dog extends Mammal {
static description = "A man's best friend"
constructor() {
super() //adds Animal and Mammal to classes
this.classes.push(Dog)
}
}
class Cat extends Mammal {
static description = "A furry purry companion"
constructor() {
super() //adds Animal and Mammal to classes
this.classes.push(Cat)
}
}
let fido = new Dog()
fido.classes.forEach(function(i) {
console.log(i.description)
}
我希望類只接受 Animal 和擴展 Animal 的類。
uj5u.com熱心網友回復:
給定一個物件實體,您可以沿著原型鏈向上走:
function describe(animal: Animal) {
for (let prototype = Object.getPrototypeOf(animal); prototype !== Object.prototype; prototype = Object.getPrototypeOf(prototype))
console.log(prototype.constructor.description);
}
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/371202.html
下一篇:嘗試訪問頭函式中的私有類變數
