thomasfrank.se

Object.prototype is erlaubt

July 13, 2006

It is not seldom that you see people messing with Object.prototype. This is because it is an extremely handy way of learning JavaScript new tricks and write cost effective code.
Some might say it is verboten, because it breaks their for-in-loops, and their if(member in obj) checks. Most of those people know it is easy to include extra checks in your code to make sure this doesn't become a problem. So why do they persist it's verboten?
I hope it is not because they are overly religious, but because they are soundly lazy. After all, the prime sign of a good programmer is, that he/she/it is lazy -- "the three chief virtues of a programmer are: laziness, impatience and hubris" (Larry Wall).
I'm lazy too. But in my world two lazy approaches collide when it comes to the Object.prototype. I want to use it, because I'm lazy, but I don't want to write extra checks every time I use a for-in-loop, because I'm lazy. I knew I could come up with a good solution to this (hubris), I did (impatience) and here it is.

The problem

Consider the following piece of code (or try it out). Both the for-in-loop and the if--in checks return the Object.prototype member "bad":
Object.prototype.bad=1;

test=function(){
	var obj={good:1}; 
	var r="";
	if("good" in obj){r+="Good.\n"};
	if("bad" in obj){r+="Bad.\n"};
	for(var i in obj){
		if(i=="good"){r+="Good too.\n"};
		if(i=="bad"){r+="Bad too.\n"}
	};
	alert(r)
};

test();

The lazy solution

Now add this little script (inClean.js, 1 kB) to your library and add the following lines of code to our previous example (try it out):
test=test.inClean();
test();

Now the "bad" member is not detected by the for-in-loop or the if--in check.

How does that work?

The inClean method returns a modified version of your function, where it makes sure that all for-in-loops and if-ins does not detect Object.prototype members.

Getting back to normal

If you want your function/method to get back to normal and include Object.prototype members again you just reset it like this:
test=test.inNormal();

Don't worry, be happy

I think the above example proves that checking for Object.prototype members does not have to clutter your code or make it any less readable.
But I bet some will still not agree that extending the Object.prototype is erlaubt. They just might not be lazy enough. Or they might have turned this whole verboten thing into a question of faith.
But the rest of us can be happy, lazy and get on wih some constructive programming, without having to dismiss one of the coolest feautures of JavaScript -- the possibility to extend the Object.prototype.
[comments]