Javascript: Adding functionality to built-in classes

Jan 20 by Andre
Strings, arrays, and all other classes in Javascript are extensible, and it's extremely easy to add methods to them. An example is the best way to demonstrate; this example shows a "trim" method (strip whitespace from the beginning and end of string) added to the built-in "string" class:
String.prototype.trim = function () {
  var sNew = this.replace(/^\s*/, ""); // strip whitespace from the beginning of the string
  sNew = sNew.replace(/\s*$/, ""); // strip whitespace from the end of the string
  return sNew; // return the mutated string
}
You can call the method on any instance of string:
var sString = "a value from an HTML form . . . ";
sString = sString.trim();

What you need to know: Prototypes and the "this" keyword

Everything in Javascript has a prototype. Any functions you add to the prototype are automatically available to each and every instance of the class. Accessing the prototype is as easy as specifying [class].prototype. So in the example above, we added a function (trim) to string's prototype: string.prototype.trim=function(){...};

The other key is the "this" keyword. Whenever you are coding a "prototype" function, you need access to the particular instance. The "this" keyword lets you do it. At runtime, the "this" keyword resolves to the actual instance of the object, in this case a String.

Note that this example does not mutate the string on which you called the method. Rather, it returns a new string with whitespace removed. The original instance is left unchanged. If you were to do the following:

var sString = " a value from an HTML form . . . ";
sString.trim();

. . . sString would not change. Calling the trim() method would produce a new string, which would then be thrown away because it isn't being assigned to anything.

Post a comment

 
This is so filters can reject the spam-bots. Thanks!