Created
March 8, 2012 22:51
-
-
Save simondavies/e00946ae1ed64d7ce275 to your computer and use it in GitHub Desktop.
Javascript: Basic Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple JS Class Set up and usage | |
*/ | |
var MyClassName = (function(){ | |
/** | |
* Add variable here public and private | |
* I use an underscore for my private variables to separate them visually | |
*/ | |
var varName = {}, | |
_privateVar = 100; | |
/** | |
* Add Public methods here | |
*/ | |
myFirstPublicMethod = function(arg, uments){ | |
//-- to access a private method is only possible form within the class itself | |
return _myFirstPrivateMethod(23, 'ok thanks'); | |
}; | |
mySecondPublicMethod = function(arg, uments){ | |
}; | |
/** | |
* Add Private methods here | |
* I tend to add an underscore at the beginning of my private methods to separate visual form the public ones | |
*/ | |
_myFirstPrivateMethod = function(arg, uments){ | |
//-- place your method code here, the content with in the brackets are the arguments passed to the method | |
}; | |
_mySecondPrivateMethod = function(arg, uments){ | |
}; | |
/** | |
* Declare Public Variables and Methods | |
* Any public variables and methods you want need to then be initiated / returned to make these viewable | |
*/ | |
return { | |
//-- init the public variables first then the methods | |
//-- notie the first name is what wil be the viewable method/variable etc, the second references the method/variable its calling | |
//-- if you name your methods with a long description then you can use a shorter name to use for the visual aspect, see the mySecondPublicMethod | |
//-- entry below for eg | |
varName : varName, | |
myFirstPublicMethod : myFirstPublicMethod, | |
mySecondPublicMethod : mySecondPublicMethod, | |
secMth : mySecondPublicMethod | |
} | |
})(); //-- end of class | |
/** | |
* Once loaded into the page you can access it as follows | |
*/ | |
//-- create a new instance of the class | |
var myCls = new MyClassName(); | |
//-- access the public variables/methods | |
myCls.varName = 300; | |
myCls.myFirstPublicMethod(23,"hello"); | |
//-- if you try to access a private method it should fail on you see below. | |
myCls._mySecondPrivateMethod(23,"hello"); | |
//-- to access something within a private method then you will need to call it from within a public method see the myFirstPublicMethod method above | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment