Comment Re:Scoping is Awful? You need to buy the book... (Score 1) 162
Error: Implied global: doSomething 1, document 3
and
Global elements, i, onclickGenerator
1 onclickGenerator(i)
1 "return"()
Outer i
Global doSomething
Yeah, building multiple functions is a bit wasteful. I suppose you could get by by attaching new properties to the elements and having the function attached to onclick reference the objects by using the event's target/srcElement property to get back to the custom variable.
Well.. wastefull.. true, but for some apps it is detrimental (think ajax). Your example can perhaps be converted into something which avoids the need to pass "i" at all. Script libraries like YUI have code where you can control scoping when the handler executes. This may be overkill in this situation. So in this example perhaps setting an (html) id on the element and extracting it in the "doSomething" function would suffice, then you don't need the parameter at all.
function doSomething() {
var id = this.id
doSomethingElse(id);
}
then (something like)
for (var i = 0; i < elements.length; i++) {
elements[i].id = "a"+i;
elements[i].onclick = doSomething; }
But I really do recommend the screencasts, I thought I knew stuff about javascript, after having it explained (and verifed) in the screencats it is much easier to simply "use the good parts of javascript".