Javascript – Augment Types

Posted: June 19, 2010 in Javascript
Tags: ,

//JS allows basic types of the lang 2 b augmented with new functionality & this can be done on Object, Function, String, Number, Regular expressions & booleans

// Ex: Augment Function.prototype with method that makes it available for any function, which can save us typing prototype name while using
Function.prototype.method = function (name, func) {
if(!this.prototype[name])
this.prototype[name] = func;
//return this;
};

// Augment integer method to Number.prototype
Number.method(‘integer’, function () { return Math[this < 0 ? ‘ceil’ : ‘floor’](this); });

document.writeln((-10 / 3).integer() + “<br/>”);

// Augment trim method to String.prototype
String.method(‘trim’, function () { return this.replace(/^\s+|\s+$/g, ”); });
document.writeln(‘”‘ + ”    neat   “.trim() + ‘”‘);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s