Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Created September 20, 2013 18:49
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save lavoiesl/6642066 to your computer and use it in GitHub Desktop.
Save lavoiesl/6642066 to your computer and use it in GitHub Desktop.
Javascript Object.create() polyfill
// http://jsperf.com/new-vs-object-create-including-polyfill
if (typeof Object.create !== 'function') {
Object.create = function(o, props) {
function F() {}
F.prototype = o;
if (typeof(props) === "object") {
for (prop in props) {
if (props.hasOwnProperty((prop))) {
F[prop] = props[prop];
}
}
}
return new F();
};
}
@roboticstone
Copy link

Hey, thank you so much for posting this! Since this the highest ranked result in Google for an Object.create() polyfill that supports the second parameter, I would like to point out a couple of problems that I have fixed in my fork: https://gist.github.com/roboticstone/bf537252607286aa8ef6

The most important problem is that you are copying the properties from the props parameter into the F object, rather than into the new instance created when calling new F(). This means that the object finally returned will not include those properties. The new keyword creates a new object that shares the prototype of F, but it does not copy the properties of F that are not inherited from the prototype. To solve this, we need to copy those properties into the resulting object created by the new statement instead. Note that this is the correct solution, because Object.create() adds those properties to the newly created object and not to the prototype of the newly created object.

The second problem is not so serious. When you are copying the properties from props, you are just copying the property itself, but in Object.create() the second parameter is defined with a special format, such that you actually want to be copying props[prop].value . See the definition of the second property in Object.defineProperties(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties (In Mozilla's documentation for Object.create() they direct you to this page for the definition of the second parameter)

In my fork, the second revision fixes only the first problem. The third revision fixes both problems. Please consider adopting these changes so that others may benefit from this highly ranked solution. Again, thanks for taking the time to post this!

@steelx
Copy link

steelx commented Feb 24, 2017

Can you show an example usages. Since this is accepting different arguments than MDN polyfill

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment