JavaScript 允许给语言的基本类型扩充功能。 通过给Object.prototype添加方法, 可以让该方法对所有对象都可用。 这样的方式对函数、数组、字符串、数字、正则表达式和布尔值同样适用。
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
}
return this;
}
Number.method('integer', function() {
return Math[this < 0 ? 'ceil' : 'floor'](this);
});
document.writeln((-10/3).integer()); // -3
String.method('trim', function() {
return this.replace(/^\s+|\s+$/g, '');
});
document.writeln('"' + " neat ".trim() + '"');