JavaScript prototype improvements
rot.js adds several new methods to JavaScript primordial objects: Array
, String
, Number
, Date
, Object
and Function
. Some of these are ECMAScript 5
polyfills, some are purely syntactic sugar.
Array
SHOW(
["apples", "oranges", "zombies"].random(),
["apples", "oranges", "zombies"].randomize()
);
String
A more verbose explanation about how String.format
works is available on a dedicated string formatting page.
SHOW(
"hello world".capitalize(),
"hello %s, this is %s".format("world", "sparta"),
"7".lpad("0", 3),
"123".rpad(".", 6)
);
Number
The built-in modulus operator (%) yields negative results for negative arguments. Number.prototype.mod
is guaranteed to return a positive value.
SHOW(
( 15) % 7 ,
(-15) % 7 ,
( 15).mod(7),
(-15).mod(7)
);
Object
Object.create
is a standardized way to create a new object with a hidden prototype link to other given object.
var obj1 = {price: 100};
var obj2 = Object.create(obj1);
SHOW(obj2.price);
Date
SHOW(Date.now()); /* same as new Date().getTime() */
Function
var F1 = function() {};
F1.prototype.alert = function() { SHOW("hi"); }
var F2 = function() {};
F2.extend(F1);
new F2().alert();