我正在寻找一种在UserRepo
内部使用DogRepo
和Sys
的“直接”访问方法的方法。 “直接”是指this.findDog
不是this.dogRepo.findDog
。是否可以分别“传播”或混合来自UserRepo
和DogRepo
中的方法,以便我可以在Sys
中使用它们?
class RBase {
baseFind = (x: string) => (v: string) => {}
baseCreate = (x: string) => (v: string) => {}
}
class UserRepo extends RBase {
findUser = this.baseFind('user')
createUser = this.baseCreate('user')
}
class DogRepo extends RBase {
findDog = this.baseFind('dog')
createDog = this.baseCreate('dog')
}
class Sys {
example () {
this.findDog
this.createUser
}
}
我基本上是在寻找一种扩展一个以上课程的方法。
更新,我尝试了此操作,但没有成功:
export default 'example'
class RBase {
baseFind = (x: string) => (v: string) => x
baseCreate = (x: string) => (v: string) => x
}
class UserRepo extends RBase {
findUser = this.baseFind('user')
createUser = this.baseCreate('user')
}
class DogRepo extends RBase {
findDog = this.baseFind('dog')
createDog = this.baseCreate('dog')
}
interface Sys extends UserRepo,DogRepo {}
class Sys {
example () {
this.findDog('fido')
this.createUser('michael')
}
}
function applyMixins(derivedCtor: any,baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(derivedCtor.prototype,name,// @ts-ignore
Object.getOwnPropertyDescriptor(baseCtor.prototype,name));
});
});
}
applyMixins(Sys,[UserRepo,DogRepo])
const s = new Sys()
s.example()