动态调用静态方法

Suh*_*pta 0 javascript static typescript

在一个类中,有几种static方法,要调用的方法将在运行时确定。如何动态调用此方法?

export default class channel {

    // METHOD THAT WILL DYNAMICALLY CALL OTHER STATIC METHODS
    private static methodMap = {
        'channel-create' : 'create',
        'channel-user-count' : 'userCount',
        'channel-close' : 'close'
    };

    public static do(commandType:string,params: any) {
        if(channel.methodMap.hasOwnProperty(commandType)) {
            // GET NAME OF THE METHOD
            let method = channel.methodMap[commandType];
            // CALL METHOD ON THE FLY
            //return channel.call(method,params);
            // channel.userCount(params);
        }
    }
    /**
     * Adds channel to available channel list
     */
    private static create(channelName:string) {

    }

    /**
     * Returns count of users in the channel
     */
    private static userCount(channelName:string) {

    }

}
Run Code Online (Sandbox Code Playgroud)

Har*_*dha 5

您可以使用来动态调用方法Classname['methodName'](param)。与您的情况一样,您可以将create方法调用为Channel['create']('MyChannel')

这是工作示例:Typescript Playground

class Channel {

    private static methodMap = {
        'channel-create' : 'create',
        'channel-user-count' : 'userCount',
        'channel-close' : 'close'
    };

    private static create(channelName:string) {
        alert('Called with ' + channelName);
    }

    private static userCount(channelName:string) {
        alert('Usercount called with ' + channelName);
    }

    public static do(commandType: string, params: any) {
        if(Channel.methodMap.hasOwnProperty(commandType)) {
            let method = Channel.methodMap[commandType];

            return Channel[method](params);
        }
    }
}

Channel.do('channel-create', 'MyChannel');
Channel.do('channel-user-count', 1000);
Run Code Online (Sandbox Code Playgroud)

编辑:即使上述方法可行,正如@Ryan在他的回答中提到的那样,直接在map中提供功能更为简洁。

private static methodMap: MethodMap = {
    'channel-create': Channel.create,
    'channel-user-count': Channel.userCount,
    'channel-close': Channel.close,
};
Run Code Online (Sandbox Code Playgroud)