再扩展一类

问题描述 投票:0回答:1

我正在寻找一种从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()
typescript class es6-class
1个回答
0
投票

此方法有效,但不确定是否最好。

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'))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.