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?
-
4+1 for questioning Crockford, who makes far too many strongly argued religious arguments (many of which are also bad ideas IMHO).user949300– user9493002015年05月10日 05:48:09 +00:00Commented May 10, 2015 at 5:48
-
7It's a polyfill. It fills it in old (ES3) browsers.Benjamin Gruenbaum– Benjamin Gruenbaum2015年05月10日 18:15:41 +00:00Commented May 10, 2015 at 18:15
1 Answer 1
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.
-
1he doesn't ask where it's defined, but why.jwenting– jwenting2015年05月10日 15:02:08 +00:00Commented May 10, 2015 at 15:02
-
1Crockford's
Object.create
predates ES5's, so this answer is chronologically wrong.Zirak– Zirak2015年05月10日 17:30:23 +00:00Commented 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 onObject
- so this answer is not really chronologically wrong.Benjamin Gruenbaum– Benjamin Gruenbaum2015年05月10日 18:15:03 +00:00Commented May 10, 2015 at 18:15 -
1@BenjaminGruenbaum javascript.crockford.com/prototypal.html see right at the end - 2008 was before ES5Zirak– Zirak2015年05月10日 18:39:11 +00:00Commented May 10, 2015 at 18:39
Explore related questions
See similar questions with these tags.