Does a Javascript function have to be defined before calling it?

前端 未结 4 969
时光取名叫无心
时光取名叫无心 2020-12-14 16:53

If I run the function below before defining it, I will get this error...

Uncaught ReferenceError: openModal is not defined

run then def

4条回答
  •  一个人的身影
    2020-12-14 17:15

    When you assign a function to a variable, you have to assign it before you can use the variable to access the function.

    If you declare the function with regular syntax instead of assigning it to a variable, it is defined when code is parsed, so this works:

    $(document).ready( function() {
    
        delay(openModal, 2000);
    
        function openModal() {
            $('#modal-box').css( {
                left: $(window).width() / 2 - $('#modal-box').width() / 2,
                top: $(window).height() / 2 - $('#modal-box').height() / 2
            } );
            $('#modal-box').show();
            $('#modal-mask').show();
        };  
    
    });
    

    (Note the difference in scope, though. When you create the variable openModal implicitly by just using it, it will be created in the global scope and will be available to all code. When you declare a function inside another function, it will only be available inside that function. However, you can make the variable local to the function too, using var openModal = function() {.)

提交回复
热议问题