再多上一堂课

我正在寻找一种在UserRepo内部使用DogRepoSys的“直接”访问方法的方法。 “直接”是指this.findDog不是this.dogRepo.findDog。是否可以分别“传播”或混合来自UserRepoDogRepo中的方法,以便我可以在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()
a55713766 回答:再多上一堂课

这行得通,但不确定是否最好。

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'))
    }
}
本文链接:https://www.f2er.com/3136187.html

大家都在问