I have registered some javascript functions in the global scope:
function Test1() {}
function Test2() {}
Now I want to run all javascript functions whose name starts with 'Test', how to do it?
I want to prevent saving each functions into a variable because it does not scale. Nor to push them to a queue and execute them later, since people need to remember adding their functions to the queue when they write the test and I don't want that.
I have registered some javascript functions in the global scope:
function Test1() {}
function Test2() {}
Now I want to run all javascript functions whose name starts with 'Test', how to do it?
I want to prevent saving each functions into a variable because it does not scale. Nor to push them to a queue and execute them later, since people need to remember adding their functions to the queue when they write the test and I don't want that.
Share Improve this question asked Sep 24, 2018 at 22:43 yijiemyijiem 3693 silver badges18 bronze badges 7- are the functions named "Test" + number or "Test" + anything else ? – Stakvino Commented Sep 24, 2018 at 22:49
-
1
Iterate over all properties of
window
and check whether it starts withTest
? But since there are lots of things in global scope, maintaining your own list is probably better. Naming variables/functions with consecutive numbers is a string sign that you should be using an array instead. "I want to prevent saving each functions into a variable because it does not scale." Can you elaborate what you mean? – Felix Kling Commented Sep 24, 2018 at 22:50 -
I want to prevent saving each functions into a variable because it does not scale.
Can you elaborate on this, because it doesn't sound right. – Matt Way Commented Sep 24, 2018 at 22:53 - If you don't provide more/other information then this is a duplicate of Calling multiple functions with names matching Regex – Felix Kling Commented Sep 24, 2018 at 22:53
- Also related: “Variable” variables in Javascript? – Felix Kling Commented Sep 24, 2018 at 22:58
3 Answers
Reset to default 6
var globalKeys = Object.keys(window);
for(var i = 0; i < globalKeys.length; i++){
var globalKey = globalKeys[i];
if(globalKey.includes("Test") && typeof window[globalKey] == "function"){
window[globalKey]();
}
}
function Test() { console.log('test') }
Object.keys(window).filter(s => s.startsWith('Test')) // [ "Test" ]
As you can see, functions are defined on the global scope.
const isTest = s => typeof s === 'function' && s.startsWith('Test')
Object.keys(window).filter(isTest).map(t => t())
I don't know your use case entirely, but I suspect it would be better to provide your own object.
const tests = {}
tests.Test1 = () => {/*...*/}
You could get all elements of window
and check them.
Here is a basic starting point :
for(let objectName in window){
console.log(`${objectName} : ${typeof window[objectName]}`)
}
Now objectName
is actually a string, it could be anything, just check if it starts with Test
, and if its type is a function.