动态调用静态方法

时间:2017-02-16 18:08:30

标签: javascript typescript static

在一个类中有几个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) {

    }

}

3 个答案:

答案 0 :(得分:4)

您可以使用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);

编辑:尽管上述方法有效,但正如@Ryan在回答中所提到的,直接在地图中提供功能要清晰得多。

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

答案 1 :(得分:3)

将功能直接存储在地图中:

type MethodMap = { [name: string]: (any) => void };

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

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

答案 2 :(得分:0)

要添加@HardikModha的答案,您还可以让编译器根据可能的值检查commandType

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

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

Channel.do('channel-create', 'MyChannel'); // fine
Channel.do('channel-created', 'MyChannel'); // error

code in playground