Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

8. Classes > Augmenting Classes

Augmenting Classes

JavaScript’s prototype-based inheritance mechanism is dynamic: an object inherits properties from its prototype, even if the properties of the prototype change after the object is created. This means that we can augment JavaScript classes simply by adding new methods to their prototype objects. Here is code that adds a method to our Range class:

// Return a new range with negated endpoints
Range.prototype.negate = function() {
    return new Range(, -this.from);

The prototype object of built-in JavaScript classes is also “open” like this, which means that we can add methods to numbers, strings, arrays, functions, and so on. Here are some examples:

// Invoke the function f this many times, passing the
// iteration number. E.g., to print "hello" 3 times:
//   var n = 3;
//   n.times(function(n) { console.log(n + " hello"); });
Number.prototype.times = function(f, context) {
    var n = Number(this);
    for(var i = 0; i < n; i++), i);

// Define the ES5 String.trim() method if it does not 
// exist. This method trims space from the start and end.
String.prototype.trim =
    String.prototype.trim || function() {
        if (!this) return this;
        return this.replace(/^\s+|\s+$/g, "");

// Return a function's name or "". If it has a name 
// property, use it. Otherwise, convert the function to 
// a string and extract the name from that. 
Function.prototype.getName = function() {
    return ||


You are currently reading a PREVIEW of this book.


Get instant access to over $1 million worth of books and videos.


Start a Free 10-Day Trial

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint