SlightlyLoony
Tera Contributor

Have you ever wished the designers of a JavaScript class had included a method property you'd really like to have? I sure have. For instance, I've often wished that String class had a "right" and "left" method, or that the Math class had φ, the "Golden Ratio".

Just wishing for these won't make them appear — but a few lines of code will do the trick! Here's how:


String.prototype.right =
function(n) {
return this.substring(Math.max(0, this.length - n));
};

String.prototype.left =
function(n) {
return this.substring(0, n);
}

Math.golden = 1.6180339887498948482;

var x = 'Testing this thing!';
gs.log(x.left(8) + x.right(6) + ' ' + Math.golden);

If you're familiar with JavaScript classes and objects, then you should be able to figure out what's going on here. The prototype property of any class holds the (wait for it!) prototype of the methods and properties that will be available to any instance of that class. By adding functions to the prototype, we're adding methods to all instances of that class created after we added the methods to the prototype.

In the case of adding a constant to the Math class, we're not looking for an instance property, but rather a property that's available even outside the instances (as we've used it above). To do that, you simply add the property to the class object itself (in this case, Math). Note that you could add any kind of property to the class object, including a function — which then becomes a class method available for use anywhere, including outside an instance of the class.

One cautionary note: it's only guaranteed safe to add properties to the class object or its prototype object if the class in question is a standard JavaScript class, or a class that you have created. Certain kinds of classes, in some environments, can't be extended. For example, in some Microsoft browser versions, the DOM classes cannot be extended. In Service-now.com's server-side environment, Java classes exposed through the Packages... construct can't be extended. But the standard classes are all there for you to play with...

2 Comments