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;
}
@karolk
Copy link
Author

karolk commented Dec 2, 2011

How to use it:

  1. define the prototype object
var proto = {
    hello: function() {
        alert( this.name + ': hello' )
    }
};
  1. pass it to ObjectCreate
ObjectCreate( proto, {
    name: {
        value: 'Karol',
        pd: 'e'
    },
    age: {
        value: 12,
        pd: 'we'
    }
} );

This is how ES5 equivalent looks like - (not supported by IE 8 and older)

Object.create( proto, {
    name: {
        value: 'Karol',
        enumerable: true
    },
    age: {
        value: 12,
        writable: true,
        enumerable: true
    },
});

The wrapper does the EcmaScript 5 object creation for capable browsers and degrades to Douglas Crockford's pattern for older JS engines.

Special sauce:
pd string is a shorthand for property descriptor object, for example:

//'wec' is:
{
    writable: true,
    enumerable: true,
    configurable: true
}

//'c' is:
{
    configurable: true
}

@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