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&g开发者_如何学Pythont;
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.
var
defines 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 var
out when assigning to a non-existent variable always defines a global variable. Personally I prefer to define all global variables in the global scope with var
, or use window.foo
to access them, to make it explicit I wanted to use a global variable, and that I didn't leave var
out by accident.
Oh I'll answer this so imprecisely I'm going to get downvotes. For me I think of var as reseting the scope so it's only available at to others in the same scope.
What I think is interesting is what happens when you define a var in a bigger scope, then redefine it in an inner scope, monkey with that inner one a bit, then return to the outer scope. I don't know the answer, I'm sure there's a bunch of edge cases, but I do think it's a fascinating place to study.
精彩评论