I want to start this post by saying that there really is no practical use for the information presented here. One could argue that it's a great intro to JavaScript object's prototype property, but it's really meant to be humorous, the type of thing you do when a deadline isn't approaching and you really want to drive your colleagues crazy.

To do this properly, you need to have an understanding of JavaScript's core language feature, prototype. You can do so by searching for prototype within this blog, or just google it. This post isn't too bad: http://1closure.com/2012/07/object-oriented-javascript-part-2-how-the-prototype-works/

If you already know how prototype works, you know that it can be used to override "built-in" JavaScript methods and functions. Once you have that understanding, it's time to get creative.

I would say that 99% of the web applications I develop start with me loading in the jQuery library. Other developers may use other libraries. I bring this up because we'll need a hiding place for our "prank code". Within the jQuery library file itself is a great place to tuck the code, as a typical developer would never think twice about checking it.

So, what kind of things can we do to really drive our colleagues crazy?

String Manipulation

  1. Override the string replace function.

    String.prototype.replace = function() { return 'milkshake'; }

    a = 'http://www.example.com';

    a.replace('http', 'https');

    milkshake

  2. Override the a case change function.

    String.prototype.toLowerCase = function() { return this.toUpperCase(); }

    'Test'.toLowerCase()

    "TEST"

  3. Play with the built-in trim function so it actually doubles the amount of white space padding, instead of removing it.

    String.prototype.trim = function() { return this.replace(/ /g, ' '); }

    '  test  '.trim()

    "    test    "

You get the idea. You can be pretty devious and really drive a fellow developer crazy trying to figure out why his code keeps outputting the string "milkshake"!

Unfortunately, JavaScript doesn't have a very extensive collection of built-in functions. What's worse, is that you can't override the Math object functions. So, you really need to get creative!

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *