Last active
December 20, 2015 18:59
-
-
Save nbubna/6180113 to your computer and use it in GitHub Desktop.
A paranoid function for defining properties on an object such that they will never override existing ones, never error, never interrupt the current thread, and never allow subsequent definitions of the property. (requires ES5)
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 define(object, key, fn, force) { | |
if (force || !(key in object)) {// unless we're forcing the issue, avoid already defined keys | |
(setImmediate || setTimeout)(function() {// do it asynchronously to not interrupt other initialization | |
try {// suppress errors when the property isn't configurable | |
Object.defineProperty(object, key, { value: fn });// define the new one to be non-enumerable and non-configurable | |
} catch (e) {} | |
}, 0); | |
} | |
}; | |
// if you really want to get fancy, you could use promises or callbacks to resume init after this is defined. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment