简体   繁体   中英

How to execute a JavaScript Function When I have its name as a string (with parameters that have an overload argument)

I am trying to call a certain function based on variables that I pass in (scamId and actorId), and the only issue is that when I try to pass in intent2 as an argument, it does not seem to find what it needs from my repository. I got this little function builder script from How to execute a JavaScript function when I have its name as a string and I have used it for some other things and it works great, but I'm not sure how to pass in intent2 and have it create the function correctly. It works when the statement is not overloaded like if intent2 = "stuff", but not when I have it in the format below.

For example, return statement would be equivalent to if everything worked correctly -

return this.intentS1A1Repository.findOne({where: { intent: intentBase }});

    const info = this

    // how can I format this intent2 so that it works?
    const intent2 = { 
      where: 
      { intent: intentBase }
    }

    const getIntent = "intentS" + scamId + "A" + actorId + "Repository.findOne";
    
    await getIntentFunctionBuilder(getIntent, info, intent2);
    
    async function getIntentFunctionBuilder(functionName: string, context: any, args: any) {
      args = Array.prototype.slice.call(arguments, 2);
      var namespaces = functionName.split(".");
      var func = namespaces.pop();
      for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
      }
    
      return await context[func].apply(context, args);  
    }

Any help would be much appreciated!

Okay I figured it out instead of working with that crazy function, its actually much more simple than that.

    const intent2 = { 
      where: 
      { intent: intentBase }
    }

    const object = "intentS" + scamId + "A" + actorId + "Repository";
    return await this[object]["findOne"](intent2)

This little code snippet can take in OVERLOADED PARAMETERS as an argument, which is terrific. It allows you to pass in custom built functions, so you don't have to have 20 different functions that perform basically exactly the same task. The return evaluates to exactly this:

return this.intentS*A*Repository.findOne(intent2);

Hopefully you won't have to go through what I did trying to figure this out. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM