Course: JavaScript

Progress (0%)

Exercise: Object.create() Polyfill

Exercise 38 Easy

Prerequisites for the exercise

  1. JavaScript Prototypes
  2. JavaScript Constructors
  3. All previous chapters


Create a polyfill for the static Object.create() method.


In the JavaScript Objects — Prototypes chapter, we saw the Object.create() method and that how it enables one to create an object with a given prototype.

Object.create() isn't supported on old browsers, likewise to get it to work in them, we have to create a polyfill for the method.

In this exercise, you have to create a polyfill function objectCreatePolyfill() for Object.create().

It doesn't have to be a full-fledge polyfill, just have support for first proto argument. That's it.

It's not required for your polyfill to accept the second parameter of Object.create(), however if you wish to, you could — it's very easy to implement that as well.

The function objectCreatePolyfill() has the same behavior as Object.create(). Here's how it should work:

var a = { x: 10, y: 20 };
var b = objectCreatePolyfill(a);
View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-38-Object.create()-Polyfill and put the .html solution files for this exercise within it.


Recall from the chapter JavaScript Objects — Prototypes, it's possible to assign an object to the prototype property of a given constructor functoion and thus get any subsequent instance instantiated from it to inherit data from that very prototype object.

In creating a polyfill for Object.create(), this is exactly what we ought to do.

So when objectCreatePolyfill() is called with a proto argument, here's what happens:

  1. First a constructor function is created.
  2. Then, its prototype property is assigned the value proto. This effectively results in any instance being created later from this constructor to have proto as its prototype.
  3. Finally, we instantiate a new object out of this constructor and return it.

This returned object is empty since the body of the constructor is empty. Moreover, the prototype of this returned object is proto.


Shown below is the definition of objectCreatePolyfill() based on this:

function objectCreatePolyfill(proto) {
   function F() {}
   F.prototype = proto;

   return new F();

Let's now test this:

function objectCreatePolyfill(proto) {
   function F() {}
   F.prototype = proto;

   return new F();

var a = { x: 10, y: 20 };
var b = objectCreatePolyfill(a);
b.x = 500;

console.log(b.x, b.y);
500 20

It works just as desired.

Object.create() may seem a feature not capable to be polyfilled in native JavaScript. However, as we've seen, it's merely based on the idea of a constructor and prototype property.

That's it — nothing really special about it.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage