Skip to content

Instantly share code, notes, and snippets.

@tenorok
Last active December 28, 2015 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tenorok/7480866 to your computer and use it in GitHub Desktop.
Save tenorok/7480866 to your computer and use it in GitHub Desktop.
JavaScript: Private properties
/* Constructor */
function Klass(text, separator) {
this.text = text;
this.separator = separator;
this.__bind(); // Set context to private methods
}
Klass.prototype = (function() {
/* Private properties */
var _ = {
privateField: 'World',
privateMethod: function() {
return this.separator + _.privateField + Klass.staticMethod() + $.privateStaticMethod();
}
};
/* Private static properties */
var $ = {
privateStaticMethod: function() {
return ' =)';
}
};
/* Public properties */
var properties = {
publicMethod: function() {
return this.text + _.privateMethod();
}
};
/**
* Set context to private methods
* @private
*/
properties.__bind = function() {
for(var prop in _) if(_.hasOwnProperty(prop) && typeof _[prop] === 'function') {
_[prop] = _[prop].bind(this);
}
};
return properties;
})();
/* Public static properties */
Klass.staticMethod = function() {
return '!';
};
console.log(new Klass('Hello', ', ').publicMethod()); // Hello, World! =)
console.log(Klass.staticMethod()); // !
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment