Created
December 29, 2011 21:59
-
-
Save nordyke/1536397 to your computer and use it in GitHub Desktop.
Some JavaScript Patterns
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
var Class = function(){ | |
//private | |
var privateVariable = 2; | |
function privateFunction(){ | |
return 5; | |
} | |
//public | |
return { | |
publicFunction1 : function(){ | |
return privateFunction(); | |
}, | |
publicFunction2 : function(){ | |
return privateVariable; | |
} | |
}; | |
} | |
//usage | |
var myObject = new Class(); | |
myObject.publicFunction1(); //returns 5 | |
myObject.publicFunction2(); //returns 2 | |
myObject.privateFunction(); //throws error | |
myObject.privateVariable(); //throws error |
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
//Immediately Invoked Function Express (IIFE) | |
//function is wrapped in a closure, and then invoked immediately. | |
(function(){ | |
// code goes here | |
})(); |
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
//invoked immediately | |
var Class = (function(){ | |
//private | |
var privateVariable = 2; | |
function privateFunction(){ | |
return 5; | |
} | |
//public | |
return { | |
publicFunction1 : function(){ | |
return privateFunction(); | |
}, | |
publicFunction2 : function(){ | |
return privateVariable; | |
} | |
}; | |
})(); | |
//usage | |
Class.publicFunction1(); //returns 5 | |
Class.publicFunction2(); //returns 2 | |
Class.privateFunction(); //throws error | |
Class.privateVariable(); //throws error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment