This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The problem comes when I want to use the onClick event to check the input. Since the Label object has a "check" function, I would like to write onKlick="this.check();" However, once the label is written into the body of the document, the keyword 'this' is not recognized. Instead I need the name of the object. So far the only way I have figured out to do this is to make the object's name into a field (i.e., var lbl = new Label(3, idLabel, 'lbl') which is ugly and dangerous.
Is there a way to get the name of the object (not the class), or another better way to approach the problem? Thanks! Karen.
(onClick misspelled below to get around javaranch security)
The technique Eric shows here is called a closure. It can be a bit confusing, but it's a very useful technique for binding data to a function.
When an anonymous function is defined as shown, it "inherets" access to the environment in which it is defined -- in this case, the ref variable. (Note: closures do not have access to the this pointer of their enviroment which is why it is copied to ref before defining the closure).
Thank you so much! This is exactly what I needed to know. Can I ask one more question? Are there potential pitfalls of mixing appendChild, innerHTML, and/or document.write in the same function? Currently my write function is
Thank you again, Karen.
Joined: Aug 19, 2005
Thank you for the information about closures -- one of those things I'd heard about but never understood. It makes more sense now.