Javascript 'Classes' De-mystified
Here's something about Javascript that took me a while to really nail down. Since there are no class definitions (in the classical sense) in Javascript and yet everything is essentially an object, how do I define and instantiate the ever useful class in my project? Well, when you look around the web, you'll notice there are a few ways to do it, but ultimately, you may be confused by the concept of constructor functions vs. object literals (so am I). But, for simplicity's sake, lets just use constructor functions to make our classes.
After reviewing some of the documentation of MDN's Working with Objects and Douglass Crockford's awesome explanation of Private Members, I decided to put together this short, sweet, extremely simple example of what your freshly minted Javascript class might look like.
var Person = function(name){
//public
this.name = name;
//private
var private = 'private';
//privileged with access to public and private instance vars
this.abunny = function(){
alert('Look, '+ this.name + ' a bunny!');
alert('…and a '+ private + ' variable.');
}
//private function
function privateFunction(){
return 'good luck';
}
};
//create new instance of Person
var Amir = new Person('Amir');
//test access to instance vars
alert(Amir.name); //Amir
alert(Amir.private); //undefined
//test access to functions
Amir.abunny(); //Look, Amir a bunny! ..and a private variable.
Amir.privateFunction; //nothing happens, good luck with that...
Amir.privateFunction(); //TypeError: 'undefined is not a function'
Notes:
As you can see above, I'm using a simple constructor function called 'Person' that has a public property 'name' and a private variable 'private' and a privileged function 'abunny' and a private function that is only accessible to the privileged function or other private functions.
Then, I create a new instance of Person 'Amir' and use that instance to demonstrate the different levels of access from the rest of the script.
Try it out via the fiddle below and check out the links for further reading.
Peace, Hippie.
-ad
Links: