Last active
August 29, 2015 14:11
-
-
Save tistre/ef4d366cc19f56cbc74d to your computer and use it in GitHub Desktop.
How I do private and public in JavaScript. No “this”, no “new”! Drawback compared to .prototype: Objects hold copies of functions.
This file contains 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
// Factory function | |
var Greeter = function(config) | |
{ | |
// Hold public and private variables and functions in two objects: | |
var _public = { }; | |
var _private = { }; | |
// Storing "constructor" parameters in a private variable | |
_private.config = (config || { }); | |
// Private method | |
_private.getName = function() | |
{ | |
return (_private.config.name || 'unknown'); | |
}; | |
// Public method | |
_public.greet = function() | |
{ | |
alert('Hello ' + _private.getName()); | |
}; | |
// Return object with public variables and methods | |
return _public; | |
}; | |
// Usage: | |
// 1. Create an object | |
var greeter1 = Greeter({ name: 'World' }); | |
// 2. Call a public method | |
greeter1.greet(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment