0

I'm extending Object.create() to take a second argument e.g

if (typeof Object.create !== 'function') {
    Object.create = function (o,arg) {
        function F() {}
        F.prototype = o;
        return new F(arg);
    };
}

//could be multiple of these objects that hold data
var a = {
  b : 2
};

var c = function(data){
  return{
    d : Object.create(data)
  };
};

//create new instance of c object and pass some data
var newObj = function(arg){
  return(Object.create(c(arg)))
}

var e = newObj(a);
e.d.b = 5;
var f = newObj(a);
console.log(e.d.b);
console.log(f.d.b);

I'm just wondering if there are any pitfalls to using Object.create() in this way? I would do some extra checking on the arg argument in the Object.create() function if I was to use this but the main point is to find out if this causes any issues or is overkill etc..

  • possible duplicate of [Crockford's Prototypal inheritance - Issues with nested objects](http://stackoverflow.com/questions/10131052/crockfords-prototypal-inheritance-issues-with-nested-objects). In your case, it doesn't make much sense to inherit from the return object of `c()`, since that `d` property is already unique. – Bergi Jan 08 '14 at 12:49

1 Answers1

0

Yes, one very large pitfall: you're stepping on the toes of the definition!

Object.create already takes a second parameter, an object mapping keys to property descriptors.

This one is hard to polyfill in older environments, which is why it's still widely ignored, but when it becomes more ubiquitous, your shim will mismatch the standards pretty badly.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • Thanks, I did think straight off that it didn't feel right messing with it like this, should have actually looked at the documentation and I would have seen. –  Jan 08 '14 at 12:08
  • Actually, I had looked really only at your text. I just looked at the code, and you're not actually _using_ the second parameter to `Object.create`, nor could you in this implementation. (`new F(arg)` is really not going to do any more than `new F()`). So I'm a bit more confused by this now. But you shouldn't get in any trouble using `Object.create` the way you do. You simply don't need any special shim for it. You only use the first argument. – Scott Sauyet Jan 08 '14 at 12:35