Quick Tip: Private Variables in JavaScript

Javascript tutorial

Quick Tip: Private Variables in JavaScript

watch that tutorial on net.tutsplus.com

there is no preview for this tutorial

Description


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.





Watch on your iPhone

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();

Comments

No comment at this time. Be the first !

Add comment :

Pseudo *

Website

Message *


* Required fields.

 

All rights reserved © 2012 - about - contact us - legals
Our partners : Weecast.fr - Adaero.fr - Video-tuts.fr

Video-tuts.fr // improve and share your skills is a free directory of video tutorials. Every tutorials are carrefuly examined by a moderator.