如何获取作为参数传递的函数的参数?

时间:2015-10-23 11:58:57

标签: typescript

给出以下TypeScript函数:

register(action: (customData: CustomClass) => void): number {
    // get the first argument
    action.arguments.??? // <-- how to access the arguments of the function passed in?
}

被称为

someInstance.register(this.doStuff);

并将doStuff - 函数定义为

doStuff = (customData: CustomClass): void => {
    console.log(customData.someValue);
}

doStuff函数有一个customData类型的参数CustomClass

如何在register - 函数(第一个)中访问这个?

调用action.arguments内部是null,甚至在chromes dev.tools中我也无法弄清楚如何访问它。

1 个答案:

答案 0 :(得分:2)

您将该函数作为第一类对象传递,它在传递它作为“register”函数的参数时没有实参数。你应该稍后传递参数,然后你将使用(执行)这个函数:

class Test {
    _actions: Array<(customData: CustomClass) => void> = [];
    register(action: (customData: CustomClass) => void): void {
        this._actions.push(action);
    }
    executeActions(customData: CustomClass) {
        // execute all registered actions with passed customData
        this._actions.forEach(action => action(customData));
    }
}

更新1.完整示例

class CustomClass {
    constructor(public a: string = "abc") {}
}

class Test {
    _actions: Array<(customData: CustomClass) => void> = [];
    register(action: (customData: CustomClass) => void): void {
        this._actions.push(action);
    }
    executeActions(customData: CustomClass) {
        // execute all registered actions with passed customData
        this._actions.forEach(action => action(customData));
    }
}

var test = new Test();
var action = (customData: CustomClass) => {
    console.log(customData.a);
}

test.register(action);

test.executeActions(new CustomClass());