Skip to content

Instantly share code, notes, and snippets.

@nbubna
Last active December 20, 2015 18:59
Show Gist options
  • Save nbubna/6180113 to your computer and use it in GitHub Desktop.
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)
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