04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7: Anonymous Functions<br />

The constructor in this code defines two privileged methods: getName() and setName() . Each method<br />

is accessible outside the constructor and accesses the private name variable. Outside the Person<br />

constructor, there is no way to access name . Since both methods are defined inside the constructor, they<br />

are closures and have access to name through the scope chain. The private variable name is unique to<br />

each instance of Person since the methods are being re - created each time the constructor is called. One<br />

downside, however, is that you must use the constructor pattern to accomplish this result. As discussed<br />

in Chapter 6 , the constructor pattern is flawed in that new methods are created for each instance. Using<br />

static private variables to achieve privileged methods avoids this problem.<br />

Static Private Variables<br />

Privileged methods can also be created by using a private scope to define the private variables or<br />

functions. The pattern is as follows:<br />

(function(){<br />

})();<br />

//private variables and functions<br />

var privateVariable = 10;<br />

function privateFunction(){<br />

return false;<br />

}<br />

//constructor<br />

MyObject = function(){<br />

};<br />

//public and privileged methods<br />

MyObject.prototype.publicMethod = function(){<br />

privateVariable++;<br />

return privateFunction();<br />

};<br />

In this pattern, a private scope is created to enclose the constructor and its methods. The private<br />

variables and functions are defined first, followed by the constructor and the public methods. Public<br />

methods are defined on the prototype, as in the typical prototype pattern. Note that this pattern defines<br />

the constructor not by using a function declaration but instead by using a function expression. Function<br />

declarations always create local functions, which is undesirable in this case. For this same reason, the<br />

var keyword is not used with MyObject . Remember: initializing an undeclared variable always creates a<br />

global variable, so MyObject becomes global and available outside the private scope.<br />

195

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!