0

我的所有层次结构中都有一些静态的东西(在这个例子中,_image)。我希望能够访问通讯员_image而不必重复代码:

这会很棒:

class Actor {
    static _image; // I need it to be static

    method show(){  // I need it to be non-static
        this.setImage(this.class._image); //doesn't work....
    }
}

class GoodActor extends Actor {
    static _image = 'good.png'
}

class BadActor extends Actor {
    static _image = 'bad.png'
}

class MediumActor extends Actor {
    static _image = 'medium.png'
}

但它不起作用。现在我只需要:

class Actor {
}

class GoodActor extends Actor {
    static _image = 'good.png'  // I need it to be static

    method show(){   // I need it to be non-static
        this.setImage(GoodActor._image);
    }
}

class BadActor extends Actor {
    static _image = 'bad.png'  // I need it to be static

    method show(){  // I need it to be non-static
        this.setImage(BadActor._image);
    }
}

class MediumActor extends Actor {
    static _image = 'medium.png'  // I need it to be static

    method show(){  // I need it to be non-static
        this.setImage(MediumActor._image);
    }
}

假设这四个类有更多的方法。我不想show()在每个子类中重复该方法......但是我需要show()方法是非静态的并且_image静态访问的。

我已经阅读了这个问题https://github.com/Microsoft/TypeScript/issues/7673但不幸的是我不能在那里问,因为他们没有修复它就关闭了它。他们都没有谈到需要动态解析要调用的静态方法的问题。

4

2 回答 2

2

FTR,可以访问当前对象的类。它被称为constructor,而不是class,并且您需要声明它以便它具有比Function.

class Actor {
    static _image: string; // I need it to be static

    // Keep static members, remove construct signature because
    // subclasses may define constructors with different parameters. 
    "constructor": Pick<typeof Actor, keyof typeof Actor>;

    show(){  // I need it to be non-static
        this.setImage(this.constructor._image);
    }
}

class GoodActor extends Actor {
    static _image = 'good.png'
}

class BadActor extends Actor {
    static _image = 'bad.png'
}

class MediumActor extends Actor {
    static _image = 'medium.png'
}
于 2018-10-09T18:11:19.457 回答
1

更新:你为什么不想在缓存图像之前构造单个对象?如果您使构建成本低廉,则使用静态字段没有任何好处。

例子:

class Actor {
    image: string;

    showImage() {
        console.log(this.image);
    }
}


class GoodActor extends Actor {
    image = 'good.png';
}

class BadActor extends Actor {
    image = 'bad.png';
}

const myActorTypes: (typeof Actor)[] = [GoodActor, BadActor];

function preloadImages() {
    for (let myActorType of myActorTypes) {
        preloadImage(new myActorType().image);
    }
}

function preloadImage(image: string) {
    console.log(`Loading ${image}`);
}

preloadImages();

// "Loading good.png"
// "Loading bad.png"
于 2018-10-09T16:26:55.547 回答