给出以下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中我也无法弄清楚如何访问它。
答案 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));
}
}
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());