调用变量中命名的打字稿函数

时间:2017-04-20 00:48:17

标签: angular typescript

我正在开发Ionic2应用程序。我正在从一个页面调用一个函数。是否有可能在函数调用中使用变量名。 e.g。

原始代码:this._userDataService.getGrandQuestionsFromServer(this.passedId, newLevel)

预期代码::

this._userDataService.get`${this.questionModuleName}`QuestionsFromServer(this.passedId, newLevel) 

3 个答案:

答案 0 :(得分:5)

您应该可以使用括号表示法来实现此目的。这是一个有效的例子:

const obj = {
  foobar(arg) {
    console.log(arg);
  }
};

const bar = "bar";
obj[`foo${bar}`]("It works!");

在您的代码中,请尝试以下操作:

this._userDataService[`get${this.questionModuleName}QuestionsFromServer`](this.passedId, newLevel)

答案 1 :(得分:0)

有一项名为Tagged template literals

的功能
  

更高级的模板文字形式是标记模板   文字。标签允许您使用函数解析模板文字。   标记函数的第一个参数包含一个字符串数组   值。其余参数与表达式相关。在里面   结束,你的函数可以返回你操纵的字符串(或者它可以   返回完全不同的东西,如下所述   例)。可以命名用于标记的函数的名称   任何你想要的。   MDN - Template strings

您可以使用它来预处理字符串并生成所需的函数调用。

答案 2 :(得分:0)

确定你可以:

class A {
  callFunction(name:string) {
    this[`get${name}`](name);
  }

  getAmount(name: string) {
    alert(name);
  }
}

let a = new A();
a.callFunction('Amount');
相关问题