Objective
Create a polyfill for the static Object.create()
method.
Difficulty
Description
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);
New file
Inside the directory you created for this course on JavaScript, create a new folder called Exercise-35-Object.create()-Polyfill and put the .html solution files for this exercise within it.
Solution
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:
- First a constructor function is created.
- Then, its
prototype
property is assigned the valueproto
. This effectively results in any instance being created later from this constructor to haveproto
as its prototype. - 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
.
Great!
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);
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.