Skip to content

Instantly share code, notes, and snippets.

@creationix
Created March 20, 2013 16:24
Show Gist options
  • Save creationix/5206044 to your computer and use it in GitHub Desktop.
Save creationix/5206044 to your computer and use it in GitHub Desktop.
Idea to make private properties and methods non-enumerable instead of prefixing them with underscores (in ES5 and above environments of course)
Object.defineProperty(Object.prototype, "hide", {
value: function () {
[].forEach.call(arguments, function (name) {
var descriptor = Object.getOwnPropertyDescriptor(this, name);
if (descriptor.enumerable) {
descriptor.enumerable = false;
Object.defineProperty(this, name, descriptor);
}
}, this);
}
});
function Rectangle(w, h) {
this.w = w;
this.h = h;
// For some reason, we want "w" and "h" to be private properties
this.hide("w", "h");
}
Rectangle.prototype.privateMethod = function () {};
Rectangle.prototype.hide("privateMethod");
@wilmoore
Copy link

@creationix:

I can think of a couple special case uses for this. Just glancing at it, I was wondering if this wouldn't be safer if line 5 were instead:

if (descriptor.enumerable && descriptor.configurable) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment