The immorality of Javascript's "this"

I have a love/hate relationship with Javascript's "this." On the one hand, it can cause a whole page to fail by moving an anonymous function into a normal method. On the other, closures (especially in stuff like jQuery) are a humongous pain without it.

The major problem is that any function referencing "this" runs differently in different contexts. $('div').each(function() { alert(this); }) is different than $(document).ready(function(){ alert(this); }). That being said, the little .each() is pretty slick.

The fundamental theorem of universal ethics is that ethics have to be just that - universal. As a universal function, it cannot run differently in different contexts. There can be no "if user == this" branch, nor a "if user.skinColor == this.skinColor" switch. In fact, there can be no reference to "this" at all.

And that is why Javascript's "this" is immoral.

No comments:

Post a Comment