Wiktor Zychla
Wiktor Zychla

Reputation: 48250

Custom implementation of `Object.create` not involving private `function`

According to various sources, including the specs, if one was to create a custom implementation of the simpler version of Object.create then it would go like this:

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

However, as new basically creates a new instance and calls F on it, I wonder whether or not this is also correct:

if (typeof Object.mycreate2 !== 'function') {
   Object.mycreate2 = function( o ) {
      var _ = { };
      _.prototype = o;
      return _;
   }
}

Simple tests suggest that this works:

var p = { name : 'Jan', surname : 'Kowalski' };
var q = Object.mycreate2( p );

q.surname = 'Malinowski';
p.surname = 'Kowalski';

console.log( q.surname );
console.log( p.surname );

The question is: is the latter implementation correct? If no, I'd also like to know why.

I might probably know the answer: object's prototype property is read only and while it works in FireFox, it shouldn't. On the other hand, function's prototype is read-write and it can be changed.

The problem with this hypothetical answer is that I can't validate it in the specs.

Upvotes: 0

Views: 126

Answers (1)

Pointy
Pointy

Reputation: 413737

Your second function is not equivalent to the first. Setting the "prototype" property of a simple object doesn't have any effect. A better test:

 var x = Object.mycreate2({foo: "bar"});
 console.log(x.foo); // undefined

The "prototype" property of a constructor function is interesting, because it actually does have a role in establishing the inheritance chain for a constructed object.

Upvotes: 1

Related Questions