lundi 26 janvier 2015

jQuery / JavaScript Function Scope / Hoisting


Vote count:

1




I have two files containing JavaScript and jQuery functions. They are referenced on the page in this order:



<script src="js/kiosk-functions.js"></script>
<script src="js/kiosk-main-socket-handler.js"></script>


In kiosk-functions.js I had originally done this -



$(function() {
// some JavaScript functions
function isJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// some jQuery code follows...
});


Then, in kiosk-main.js I had this -



$(function() {
var socket = io();
socket.on('message', function (data) {

if(isJSON(data)) {
// do stuff
}
});
// other JavaScript and jQuery code
});


This resulted in the following error -



Uncaught ReferenceError: isJSON is not defined



Once I moved the isJSON() function out of the document ready handler in kiosk-functions.js then all was well, but left me puzzled. I read a number of the answers here on SO trying to understand what was going on, being under the impression that the function would be hoisted and available globally. I didn't find anything that demonstrated this example.


I'm sure that I am missing something simple here. Does the document ready handler (a function) keep the isJSON() function from being hoisted? Or is it a simple scope issue?



asked 1 min ago







jQuery / JavaScript Function Scope / Hoisting

Aucun commentaire:

Enregistrer un commentaire