Created
March 20, 2013 16:24
-
-
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)
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
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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: