Last active
July 11, 2019 05:55
-
-
Save kl0tl/2d89a760f5df682180a1 to your computer and use it in GitHub Desktop.
Lazy initialization with Object.defineProperty
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
var accessorDescriptor, valueDescriptor; | |
accessorDescriptor = { | |
__proto__: null, | |
get: null, set: null, | |
enumerable: true, | |
configurable: true | |
}; | |
valueDescriptor = { | |
__proto__: null, | |
value: null, | |
writable: true, | |
configurable: true | |
}; | |
function lazy(target, property, getter, options) { | |
var writable, enumerable; | |
if (!options) options = lazy.defaults; | |
if ('writable' in options) writable = Boolean(options.writable); | |
else writable = lazy.defaults.writable; | |
if ('enumerable' in options) enumerable = Boolean(options.enumerable); | |
else enumerable = lazy.defaults.enumerable; | |
accessorDescriptor.get = accessorDescriptor.set = accessor; | |
accessorDescriptor.enumerable = enumerable; | |
return Object.defineProperty(target, property, accessorDescriptor); | |
function accessor() { | |
if (arguments.length) { | |
if (writable) valueDescriptor.value = arguments[0]; | |
else return; | |
} else { | |
valueDescriptor.value = getter.call(this); | |
} | |
valueDescriptor.writable = writable; | |
valueDescriptor.enumerable = enumerable; | |
return Object.defineProperty(this, property, valueDescriptor)[property]; | |
} | |
} | |
lazy.defaults = { | |
writable: false, | |
enumerable: false | |
}; | |
function bound(target, property, method, options) { | |
return lazy(target, property, function () { | |
return method.bind(this); | |
}, options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment