通用JavaScript方法,它根据参数调用其他方法

App*_*pps 1 javascript methods dojo

我有一个Javascript方法,它需要两个参数 - 第一个是应该执行的函数的名称,第二个是params数组,我需要传递给我需要执行的函数.基本上我需要使它成为通用函数.我可以使用Dojo以高效的方式实现这一目标吗?以下是我的功能.

function UserDetails(){

    this.invokeCustomFunction=function(fnToBeExecuted,arraysOfParams){
        //This function is expectetd to execute the "fnToBeExecuted" and pass the "arraysOfParams" to it.
    }

    this.getUserDetails=function(userName){

    }

    this.getSalaryDetails=function(userId,EmployerName){

    }
}
//This is how I invoke it.
UserDetails userDetails=new UserDetails();
userDetails.invokeCustomFunction("getUserDetails","Sally");
userDetails.invokeCustomFunction("getSalaryDetails",["Sally","ATT"]);
Run Code Online (Sandbox Code Playgroud)

N3d*_*st4 7

你的例子并不清楚你为什么要这样做,但如果你真的这样做,那么:

this.invokeCustomFunction=function(fnToBeExecuted,arraysOfParams){
    this[fnToBeExecuted].apply(this, arraysOfParams)
}
Run Code Online (Sandbox Code Playgroud)

  • +1这里是[`apply`功能文档](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Apply). (3认同)