Skip to content

Instantly share code, notes, and snippets.

@tistre
Last active August 29, 2015 14:11
Show Gist options
  • Save tistre/ef4d366cc19f56cbc74d to your computer and use it in GitHub Desktop.
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.
// 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