Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a function exists with its name in a string?

Tags:

javascript

I create functions in Javascript dynamically. Sometimes I need to check if a certain function is actually already created.

I have the name of the function as a string. How can I check whether a function exists based on a given value in a string?

like image 754
Dylan Avatar asked Dec 21 '11 15:12

Dylan


People also ask

How do you check if a function exists or not?

Please, some explanation. In two cases, simply call function_exists with the name of function parameter to check existence, returns bool.

What function should I use to see if another function with a specific name exists?

You could directly execute it with eval() such as eval(functionName + "()") or you could get a reference to the function with eval("let fn = " + functionName) and then use the newly defined fn variable to call the function.

How do you check if a method exists on an object JavaScript?

Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance. myMethod === 'function') {} . The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.


1 Answers

You can check whether it's defined in the global scope using;

if (typeof window[strOfFunction] === "function") {     // celebrate     //window[strOfFunction](); //To call the function dynamically! } 
like image 79
Matt Avatar answered Sep 19 '22 13:09

Matt