Understanding Crockford’s Object.create shim

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
var oldObject={prop:'Property_one' }; // An object
var newObject = Object.create(oldObject); // Another object

In the above example we’ve created a new object newObject using create method which is a member function of Object object that we’ve added in the Object object earlier in our (Crockford’s) example. So basically what it does is that, the create method declares a function F, an empty object every function is a first class object in javascript and then we’ve inherited the prototype of o (in that case o is also an object oldObject passed as the parameter of create method) and finally we’ve returned the new object (an instance of F) using return new F(); to the variable newObject, so now newObject is an object that inherited the oldObject. Now if you write console.log(newObject.prop); then it’ll output Property_one because our newObject object has inherited the oldObject and that’s why we’ve got the value of prop as Property_one. this is known as prototypical inheritance.

You must pass an object as the parameter of create method

Leave a Comment