|
||
| Inside Technique : Form Validation Made Easy : Anonymous Functions Using the Function constructor is a handy way to piece together separate pieces of code or create a function on the fly: unfortunately, there are a number of limitations. The most important limitation is that the entire function body must be enclosed in quotes. Escaping the entire function body can become quite tedious and lead to code obfuscation. Anonymous functions, or function literals, are basically temporary (locally scoped) variables. Using them prevents name collisions on a page with a slew of pre-existing code, which becomes more of an issue with several developers contributing to the same pages, all of whom are following a rigid naming standard. Let's take a quick look at a simple example. Here is the same function written three ways:
So what's the difference? The Function constructor (1) parses the body and creates a new function object each time it is called. It is also scoped as a top-level function (global to the document). It allows you to create a function at runtime with a variable body. If the constructor is called in a loop, the resulting creation of many new objects becomes increasingly inefficient. The second is the standard way of declaring a function via a statement. It is completely static. A problem with this method is that multiple functions on the same page could have conflicting names. The anonymous function (3) is static just like a function declared with a statement (2). It is scoped locally, which is easier on memory consumption. Anonymous functions declared inside loops are not compiled each time through the loop, rather only the first time through. Now that you know what an anonymous function is, let's see one in action. The next page describes the use of anonymous functions to create your own methods. Page 1:Form Validation Made Easy © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |