I’ve started playing with Dojo a bit and I’m curious about variable scope issue that I’ve experienced.
I have the following code:
<div dojoType="dijit.form.Button">
<script type="dojo/method" event="onClick" args="evt">
console.dir(lastSelectedItem);
</script>
Rename
</div>
<div dojoType="dojo.data.ItemFileReadStore" url="/js/treeData.json" jsId="ordJson"></div>
<div dojoType="dijit.tree.ForestStoreModel" rootLabel="Order" store="ordJson" jsId="ordModel"></div>
<div dojoType="dijit.Tree" id="ordTree" model="ordModel">
<script type="dojo/method" event="onClick" args="item">
lastSelectedItem = item;
</script>
</div>
If I leave it at that, it works fine. However, if I replace lastSelectedItem with “var lastSelectedItem”, lastSelectedItem will not be visible in the scope where console.dir(lastSelectedItem) is called. What effect does “var” have in this case, I thought that it is put implicitly anyway?
Thanks.
vardefines a variable in the current scope. If you’re inside a function (event handlers are functions), it defines a local variable that only exists within that very function. If you’re outside a function, it defines a global variable.Leaving
varout when assigning to a non-existent variable always defines a global variable. Personally I prefer to define all global variables in the global scope withvar, or usewindow.footo access them, to make it explicit I wanted to use a global variable, and that I didn’t leavevarout by accident.