Skip to content

Instantly share code, notes, and snippets.

@karolk
Created December 2, 2011 16:13
Show Gist options
  • Save karolk/1423791 to your computer and use it in GitHub Desktop.
Save karolk/1423791 to your computer and use it in GitHub Desktop.
Object.create wrapper with shorter property descriptor syntax and graceful handling for browsers not supporting it
function ObjectCreate(proto, properties) {
var propDesc = {}, p, pd, pdStr, ES5 = !!(Object.create && Object.defineProperties);
if (!ES5) {
var F = function() {};
F.prototype = proto;
var o = new F();
}
for (p in properties) {
pd = properties[p], pdStr = pd.pd.toLowerCase();
if (ES5) {
propDesc[p] = {
value: pd.value,
writable: pdStr.indexOf('w')>=0,
enumerable: pdStr.indexOf('e')>=0,
configurable: pdStr.indexOf('c')>=0
};
}
else {
o[p] = pd.value
}
}
return ES5 ? Object.create(proto, propDesc) : o;
}
@BrendanEich
Copy link

You asked on twitter. No problems, one suggestion:

        propDesc[p] = {
            value: pd.value,
            writable: pdStr.indexOf('w') >= 0,
            enumerable: pdStr.indexOf('e') >= 0,
            configurable: pdStr.indexOf('c' )>= 0
       }

Performance is not an issue until profiling says so but this seems cleaner and it will make one "hidden class" or "inferred type" instead of several for the 'wec' combinations actually used.

/be

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment