When
users enter their name, e-mail address, and URL, they are remembered the next time they visit
the site. Once the namespace is declared, each of the methods gets attached to that object.
// declare the namespace
var SNOOK = {};
SNOOK.prepareCommentForm = function(){ /* initializes fields */ }
SNOOK.prepareField = function(options) { /* attaches event handlers, etc. */ }
SNOOK.setCookie = function(name, value, expires){ /* sets a cookie */ }
SNOOK.getCookie = function(name){ /* retrieves the value of a cookie */ }
SNOOK.remember = function(fld){ /* remembers the user-entered data*/ }
Closures
One of the vastly misunderstood features of JavaScript is its use of closures. With a closure,
a child function has access to the environment of the parent function, even after the parent
function has completed execution. In Figure 3-1, functions A and B have access to the variables
and functions declared within the window object. Likewise, if functions C and D are
declared within function B, they have access to all the variables and functions declared within
the window object and also those within function B. Any functions declared within function C
have access to all variables and functions all the way up the tree.
Figure 3-1. How closures create a hierarchy of variable and function access
The most common example of closures involves declaring event handlers:
function attachBehavior(){
var element = document.
Pages:
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126