Bob Ralian Bob Ralian - 3 months ago 6x
Javascript Question

Augmenting types in JavaScript

I'm reading Douglas Crockford's JavaScript: The Good Parts, and I'm a little confused about something. In chapter 4, under Augmenting Types, he creates a shortcut for adding a method.

Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;

He says:

By augmenting Function.prototype with a 'method' method, we no longer
have to type the name of the prototype property. That bit of ugliness
can now be hidden.

He then goes on to use this to add an 'integer' method to the number prototype with this.

Number.method('integer', function () {
return Math[this < 0 ? 'ceil' : 'floor'](this);

document.writeln((-10 / 3).integer()); // -3

I'm a little confused here... because we added a 'method' method to the Function prototype, not the Number prototype. And to my knowledge, the Number object does not inherit from the Function prototype (though maybe I'm wrong there). I see that this works, but I don't understand why Number objects are able to make use of this 'method' method to add... methods.


I assume this works because Number is a function.

As shown here: