javascript - 按属性动态调用对象中的方法
问题描述
我有一个组件接收一些参数并需要调用 params 中提供的函数。问题是函数是动态的,所以我需要在发送它们之前定义它们。
这是可以传递给组件的参数
export class SomeConfig {
baseScope: any;
functions?: { buttonName: string, buttonEvent: string, buttonFunction: Function}[]
}
这就是我填充参数并将其传递给组件的方式。如您所见,我可以通过填充buttonFunction属性来定义我想要的功能。
ngOnInit(): void {
this.gridconfig = {
baseScope : this,
functions: [
{ buttonName: 'data-edit', buttonEvent: 'click', buttonFunction: this.edit},
{ buttonName: 'data-del', buttonEvent: 'hover', buttonFunction: this.delete},
]
};
});
}
edit(){
}
delete(){
}
现在我有 mainScope 和函数。我想在 mainScope 中找到方法。
this.someconfigs.functions.forEach(fnc => {
//here i have fnc.buttonFunction which defined before and exists in this.someconfigs.mainScope
//i need to find fnc.buttonFunction in mainScope and called it dynamically, for example calling edit
})
目前,我正在使用以下语法。我将范围传递给函数
fnc.buttonFunction(this.someconfigs.baseScope);
在我的函数中,我有一个使用主范围的参数
edit(scope: any) {
//instead of this.someproperties I use scope.someproperties I want to call it directly in order to remove passing scope parameter
console.log("called");
}
我想直接调用它以删除传递的范围参数
解决方案
您可以使用Function.prototype.bind
edit() {
console.log("called");
console.log(this.someproperties);
}
fnc.buttonFunction.bind(this)();
或者只是在声明函数时绑定范围:
{
buttonName: 'data-del',
buttonEvent: 'hover',
buttonFunction: this.delete.bind(this),
},
推荐阅读
- asp.net-core - 具有多个 SUM 的 ASP.NET Core Entity Framework SELECT
- html - 使用 *ngFor 创建多个单选按钮
- css - box-shadow 没有被应用到表头
- docker - Dockerfile 入口点二进制设置为环境变量
- firebase - Firestore 检索多个文档安全规则
- nginx - Kubernetes - 入口配置,两条路径重定向到不同的命名空间
- python - Apache2服务器页面没有响应
- python - 过滤并取出日期的某些元素
- python - 在多级和多级继承中使用 super()
- java - 我需要从异步 lambda RabbitMQ 中获取价值