We are building a new experience for our SmartBear Community.
This site is now read-only. You can still browse and search as usual. Learn More

Forum Discussion

Novari-QA's avatar
Novari-QA
Frequent Contributor
9 years ago
Solved

Call function from string value JavaScript

I was hoping that TestComplete offered a method in which we can dynamically call specific functions based off of a string variable.

 

For example: This is how I would do it in C#. Unfortunately I am not sure if JavaScript has something similar, or even if TestComplete offers it.

 

using System;
using System.Reflection;

/// <summary>
///     Will invoke the method passed in. Then, it will return the generic type used in the function
///     Example: InvokeMethod<int>("methodName", "param");
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="methodName"></param>
/// <param name="stringParam"></param>
/// <returns></returns>
public static T InvokeMethod<T>(string methodName, string stringParam)
{
        return (T)typeof(T).InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
                                              null, null, new Object[] { stringParam });
}

 

 

Thoughts?

  • There are a few ways.

     

    1) Square bracket notation:

    var method = "Message";
    Log[method]("test");

    2) https://support.smartbear.com/testcomplete/docs/reference/language/javascript/call-method.html:

    Log.$call("Message", "test");

    3) https://support.smartbear.com/testcomplete/docs/reference/program-objects/aqobject/callmethod.html:

    aqObject.CallMethod(Log, "Message", "test");

3 Replies

  • There are a few ways.

     

    1) Square bracket notation:

    var method = "Message";
    Log[method]("test");

    2) https://support.smartbear.com/testcomplete/docs/reference/language/javascript/call-method.html:

    Log.$call("Message", "test");

    3) https://support.smartbear.com/testcomplete/docs/reference/program-objects/aqobject/callmethod.html:

    aqObject.CallMethod(Log, "Message", "test");
  • NisHera's avatar
    NisHera
    Valued Contributor

     

    dose https://stackoverflow.com/questions/969743/how-do-i-call-a-dynamically-named-method-in-javascript serve your purpose?

  • sergi's avatar
    sergi
    Frequent Contributor

    Additionally you can use eval function.

     

    https://www.w3schools.com/jsref/jsref_eval.asp

     

     

    Two examples of use of both eval and the other method mentioned before:

    eval("Log.Checkpoint('Hello Logger!')");
    Log["Checkpoint"]("Hello Logger!");