Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do jQuery and JavaScript have different namespaces?

I have this code in jQuery..

$(document).ready(function(){ 

var fieldCounter = 0;  ...

I have a jQuery function that increments this value.

This works, but I can't access this value on the page from a non-jQuery function? The reverse is also true, if I scope it in JavaScript e.g.

<script type="text/javascript">

var fieldCounter = 0;

I can access it from javascript but jQuery can't view it?

I'm probably doing something really dumb?

like image 812
Brett Avatar asked Dec 22 '22 04:12

Brett


2 Answers

It has nothing to do with jQuery, but all with Javascript scope.

$(document).ready(function() { 
   var fieldCounter = 0;
});

fieldCounter is declared inside a function. Since Javascript has function scope, the variable is not visible outside the function.

BTW, jQuery is Javascript, they play by the same rules, they're not two different technologies.

Exhaustive answers can be found here: What is the scope of variables in JavaScript?

like image 166
deceze Avatar answered Jan 08 '23 01:01

deceze


jQuery is not magic. It is a JavaScript library. Your issue is that you're defining a local variable inside a function. Due to the way JavaScript lexical scoping works, you can't access it outside that function (with the exception of closures, which does not apply here).

Most likely, you just want:

$(document).ready(function(){ 

fieldCounter = 0;

That will make it a global variable.

Edit: Note that using a namespace and/or declaring the global variable is cleaner, but not required.

like image 40
Matthew Flaschen Avatar answered Jan 08 '23 02:01

Matthew Flaschen