JavaScript - Obscure Stuffs
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
JavaScript allows the basic types of the language to be augmented. In chapter
3, we saw that adding a method to Object.prototype makes that method available
to all objects. This also works for functions, arrays, strings, numbers,
regular expressions, and booleans. By augmenting Function.prototype, we can
make a method available to all functions. By augmenting Function.prototype with
a method named 'method', we no longer have to type the name of the prototype
property. That bit of ugliness can now be hidden.
JavaScript does not have a separate integer type, so it is sometimes necessary
to extract just the integer part of a number. The method JavaScript provides
to do that is ugly. We can fix that by adding an 'integer' method to
Number.prototype:
Number.method('integer', function() {
return Math[this < 0 ? 'ceiling' : 'floor'](this);
});
Basically, the:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
code adds a function named 'method' to the Function.prototype object, and this
function is accessible to all functions (the typeof operator for Number and String
returns 'functions'). The function named 'method', when invoked, takes two
parameters, a name that we want to give a a function, and a function. It then
add that function to the prototype.
page revision: 0, last edited: 02 Dec 2016 06:36