8

I'm a fairly experienced programmer in the .NET and Java realms, and I've started reading up on JavaScript. I bought Douglas Crockford's "The Good Parts" book, and I'm immediately put off by a few things.

One is modifying the fundamental types without need:

if (typeof Object.create !== 'function') {
    Object.create = function (o) { //Really... 'o'? For a parameter you're only using twice?
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

Obviously creating a function with this purpose is useful and saves time, but WHY ON EARTH is he recommending creating it on Object? Three breaths ago he espoused that globals are evil, and then he proceeded to monkey patch Object. He even tests if it already exists, and just assumes that if some other library did it for him the implementation is the same.

Is there some reason not to create this in the JS equivalent of a namespace? ie

MY_UNIQUE_UTIL_LIBRARY.create = function(obj){...}; //The name would be shorter in reality.

Don't get me wrong, I think monkey patching is useful, but it's something you do when there's an inherent benefit. I don't see one here? Is there one?

Casey
  • 189
  • 2

1 Answers1

8

Object.create is defined in newer versions of browsers (can't say exactly since when). You can see its description on the Mozilla developer network.

This is just a polyfill (quite similar to the one on that page, with a few less checks) to be able to use the same function on older browsers. On newer browser it is already defined as a function and will thus use the browser optimized version, while on older browsers it is by default undefined and will use this version.

user2313067
  • 437
  • 1
  • 3
  • 7