Forgot your password?
typodupeerror

Comment Re:Scoping is Awful? You need to buy the book... (Score 1) 162

Hm, I disagree. I pasted the above code, using default settings on the jslint page, and I got:
Error: Implied global: doSomething 1, document 3
and
Global elements, i, onclickGenerator
1 onclickGenerator(i)
1 "return"()
Outer i
Global doSomething

/*members getElementsByTagName, length, onclick */

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 /* lets say id is a1*/
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".

Slashdot Top Deals

Doubt is a pain too lonely to know that faith is his twin brother. - Kahlil Gibran

Working...