首页 > 解决方案 > 按属性动态调用对象中的方法

问题描述

我有一个组件接收一些参数并需要调用 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");
}

我想直接调用它以删除传递的范围参数

标签: javascriptangulartypescript

解决方案


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

推荐阅读