Douglas Crockfords “Object.create()”

I think I’ve seen this before, but probably forgot about it somehow. Today I noticed it again somewhere on stackoverflow.com (That’s me over there.)

It’s a neat little technique developed by Douglas Crockford to quickly inherit an object from another one as its prototype:

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

Now, if you want to have a new object that has some existing object as it’s prototype, you can just do this:

newObject = Object.create(oldObject);

newObject will now have all methods and properties of oldObject. Keep in mind that oldObject the prototype of newObject are actually exactly the same.

THIS IS NOT CLONING!

So if you change a property of newObject, it will also change on oldObject. It may cause severe headache to debug something like that, if you forget it.

A more detailed article about this technique can be read here at Douglas Crockfords site.

Take care and have fun with your prototype chains ;)