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
Help

Chapter 2: Javascript Primer > Augmenting Types

AUGMENTING TYPES

JavaScript allows the facility for binding methods and other properties to built-in types, such as strings, numbers, and arrays. Strings, just like any other object, have prototypes. You can also augment String with convenience methods. For example, String has no method for converting the string “false” or “true” to a Boolean. You can add this capability as the following code demonstrates:

image
String.prototype.boolean = function() {
  return “true” == this; 
};
 
var t = 'true'.boolean();
var f = 'false'.boolean();
 
console.log(t);
console.log(f);
 
true
false

Code snippet is from string-boolean.txt

Admittedly, it’s annoying to have to redundantly type prototype every time you want to add a method. Douglas Crockford has a neat bit of code for getting around this, which augments the Function.prototype with a method called, method (please pardon the redundancy.) This is shown in the following code sample.


  

You are currently reading a PREVIEW of this book.

                                                                                        

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

  

Start a Free Trial