Created
          December 2, 2011 16:13 
        
      - 
      
 - 
        
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
  
        
  
    
      This file contains hidden or 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 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; | |
| } | 
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
  
            
How to use it:
This is how ES5 equivalent looks like - (not supported by IE 8 and older)
The wrapper does the EcmaScript 5 object creation for capable browsers and degrades to Douglas Crockford's pattern for older JS engines.
Special sauce:
pdstring is a shorthand for property descriptor object, for example: