How do I automate the process of getting an instance created and its function executed dynamically?
Thanks
Edit: Need an option to pass parameters too. Thanks
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
To use dynamic function name in JavaScript, we can create an object with the function name. const name = "myFn"; const fn = { [name]() {} }[name]; to set the fn variable to a function with the name name . We put the name method in the object and then we get the method with [name] .
The JavaScript call() Method The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.
Do you just want to call a parameterless constructor to create the instance? Is the type specified as a string as well, or can you make it a generic method? For example:
// All error checking omitted. In particular, check the results // of Type.GetType, and make sure you call it with a fully qualified // type name, including the assembly if it's not in mscorlib or // the current assembly. The method has to be a public instance // method with no parameters. (Use BindingFlags with GetMethod // to change this.) public void Invoke(string typeName, string methodName) { Type type = Type.GetType(typeName); object instance = Activator.CreateInstance(type); MethodInfo method = type.GetMethod(methodName); method.Invoke(instance, null); }
or
public void Invoke<T>(string methodName) where T : new() { T instance = new T(); MethodInfo method = typeof(T).GetMethod(methodName); method.Invoke(instance, null); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With