我正在寻找一种从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()
此方法有效,但不确定是否最好。
interface Sys extends UserRepo, DogRepo {}
class Sys {
constructor() {
Object.assign(this, new UserRepo())
Object.assign(this, new DogRepo())
}
example () {
console.log(this.findDog('fido'))
console.log(this.createUser('michael'))
}
}