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?

2
  • 4
    +1 for questioning Crockford, who makes far too many strongly argued religious arguments (many of which are also bad ideas IMHO).
    – user949300
    Commented May 10, 2015 at 5:48
  • 7
    It's a polyfill. It fills it in old (ES3) browsers. Commented May 10, 2015 at 18:15

1 Answer 1

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.

4
  • 1
    he doesn't ask where it's defined, but why.
    – jwenting
    Commented May 10, 2015 at 15:02
  • 1
    Crockford's Object.create predates ES5's, so this answer is chronologically wrong.
    – Zirak
    Commented May 10, 2015 at 17:30
  • 1
    @Zirak before that it was called beget and he defined it in whatever scope he was in and not on Object - so this answer is not really chronologically wrong. Commented May 10, 2015 at 18:15
  • 1
    @BenjaminGruenbaum javascript.crockford.com/prototypal.html see right at the end - 2008 was before ES5
    – Zirak
    Commented May 10, 2015 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.