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

后端 未结 3 1497
情话喂你
情话喂你 2020-12-15 15:45

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 a

相关标签:
3条回答
  • 2020-12-15 16:06

    We're adding our 2 cents because the accepted answer is right, but benefits from a little clarification:

    window["myFunctionNameHere"] is one simple way to solve the problem, but basically considering window as any global object accessible in the desired scope. Additionally, you must be sure to actually ASSIGN the function properly in such scope, of course.

    In the case of window, for example, you'll first need

    <script>
        $(document).ready(function () {
            window.myFunctionNameHere = function() {
                console.log('Hello world');
            }
        });
    </script>
    

    After this, the

    typeof window["myFunctionNameHere"] === "function"
    

    Will work as expected.

    0 讨论(0)
  • 2020-12-15 16:07

    You can use eval:

    if ( eval("typeof stringFunction === 'function'") ){ /*whatever*/ }
    
    0 讨论(0)
  • 2020-12-15 16:19

    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!
    }
    
    0 讨论(0)
提交回复
热议问题