04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7: Anonymous Functions<br />

A privileged method is a public method that has access to private variables and/or private functions. There<br />

are two ways to create privileged methods on objects. The first is to do so inside a constructor, as in this<br />

example:<br />

function MyObject(){<br />

//private variables and functions<br />

var privateVariable = 10;<br />

function privateFunction(){<br />

return false;<br />

}<br />

}<br />

//privileged methods<br />

this.publicMethod = function (){<br />

privateVariable++;<br />

return privateFunction();<br />

};<br />

This pattern defines all private variables and functions inside the constructor. Then privileged methods<br />

can be created to access those private members. This works because, when defined in the constructor, the<br />

privileged methods become closures with full access to all variables and functions defined inside the<br />

constructor ’ s scope. In this example, the variable privateVariable and the function<br />

privateFunction() are accessed only by publicMethod() . Once an instance of MyObject is created,<br />

there is no way to access privateVariable and privateFunction() directly; you can do so only by<br />

way of publicMethod() .<br />

You can define private and privileged members to hide data that should not be changed directly, as in<br />

this example:<br />

function Person(name){<br />

this.getName = function(){<br />

return name;<br />

};<br />

}<br />

this.setName = function (value) {<br />

name = value;<br />

};<br />

var person = new Person(“Nicholas”);<br />

alert(person.getName()); //”Nicholas”<br />

person.setName(“Greg”);<br />

alert(person.getName()); //”Greg”<br />

194

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

Saved successfully!

Ooh no, something went wrong!