Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Last active November 2, 2022 10:59
Show Gist options
  • Save kl0tl/9a8a497db45d1c97ea60 to your computer and use it in GitHub Desktop.
Save kl0tl/9a8a497db45d1c97ea60 to your computer and use it in GitHub Desktop.
Private properties using Object.defineProperty and the .caller property of functions
function $private(object, property, descriptor) {
var getter = descriptor.get;
var setter = descriptor.set;
var value = descriptor.default;
var enumerable = Boolean(descriptor.enumerable) || false;
var configurable = Boolean(descriptor.configurable) || false;
var $descriptor = {
__proto__: null,
enumerable: enumerable,
configurable: configurable
};
if (getter) $descriptor.get = function $get() {
if (assertCalledBy(getter, $get)) {
return value;
}
};
if (setter) $descriptor.set = function $set(newValue) {
if (assertCalledBy(setter, $set)) {
value = newValue;
}
};
return Object.defineProperty(object, property, $descriptor);
function assertCalledBy(caller, f) {
if (f.caller === caller) return true;
throw new Error('Unauthorized access to the private \'' + property + '\' property');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment