Advertisement
Advertisement
Advertisement
by Jeffrey Way
Difficulty:IntermediateLength:QuickLanguages:
Because of JavaScript's dependence upon globals, it might be easy to forget that creating private variables can be accomplished quite simply, thanks to closures. In just a few minutes, I'll demonstrate two common techniques which allow for private variables and methods in your projects.
The key to this particular method is to create a variable that is equal to the returned value of a function. That way, we can specifically choose with values and methods are available to our object. Thanks to closures, we'll still have access to these private variables, even after the object has been returned from our singleton.
var MyObj = function() { // Private variables var priv1 = 'private 1', priv2 = 'private 2'; // Only the methods and properties within this object will be available. return { doSomething : function() { // alert(priv1); // private 1 alert(this.someProp); // someValue }, someProp : 'someValue' } }(); // execute the function when the MyObj variable is initialized. MyObj.doSomething();
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.
Advertisement
Advertisement
Weekly email summary
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.Advertisement
Translations
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this postPowered by![Native Native]()

Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.