Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

Uncaught ReferenceError: openModal is not defined 

run then define

$(document).ready( function() {      delay(openModal, 2000);      delay = function (f, t) {         setTimeout(function() {             f();         }, t);     };      openModal = function () {         $('#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();     };    }); 

Now if I define the function first and then call it it works...I have a background in PHP so I am used to being able to access functions globally, am I doing something wrong or do all functions have to be defined before they can be used?

$(document).ready( function() {      delay = function (f, t) {         setTimeout(function() {             f();         }, t);     };      openModal = function () {         $('#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();     };        delay(openModal, 2000);  } ); 
like image 470
JasonDavis Avatar asked Apr 02 '12 08:04

JasonDavis


1 Answers

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() {.)

like image 83
Guffa Avatar answered Oct 16 '22 14:10

Guffa