Last active
November 2, 2022 10:59
-
-
Save kl0tl/9a8a497db45d1c97ea60 to your computer and use it in GitHub Desktop.
Private properties using Object.defineProperty and the .caller property of functions
This file contains 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
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