0

I am having SetUpTest() method, function name will be generated on-load of script by fetching window object. testShieldVal.js_name is variable,

testShieldVal = window.testObject || {};

SetUpTest = testShieldVal.js_name+"SetUp";

function SetUpTest() {
  new atoShieldVal.js_name.OnloadCallback(grecaptcha);
}

How can I define this function with dynamic name efficiently?

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
  • 3
    This seems like an XY problem; the easier solution is to put functions in an object w/ a key. – Dave Newton Jun 08 '21 at 17:44
  • What is `atoShieldVal`? What is the data type of `.js_name`? – trincot Jun 08 '21 at 17:50
  • @trincot function body can be ignored, I just need function name to be taken dynamically as it changes with change window object. **`testShieldVal.js_name = "login";`** Let say, `function SetUpTest() { return "testing"; }` – Aakanksha Dahima Jun 09 '21 at 13:02
  • Why not define that function on `testShieldVal`? Like `testShieldVal.setup = function () { return "testing"; };` Dynamic function names are always a bad idea. – trincot Jun 09 '21 at 13:05

1 Answers1

0

If I understand your question correctly, you are looking to define a function with a dynamic name.

In that case you should add the method to the window object using window[functionName] = function() { ... }

This results in:

testShieldVal = window.testObject || {};

SetUpTest = testShieldVal.js_name+"SetUp";

window[SetUpTest] = function {
  new atoShieldVal.js_name.OnloadCallback(grecaptcha);
}

When window.testObject.js_name is 'Demo' then Your function can then be called via DemoSetUp(). This will automatically look in the window object for a method with that name.

Vincent Bitter
  • 1,000
  • 1
  • 6
  • 15