Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Augmenting types in JavaScript

Tags:

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.

like image 752
Bob Ralian Avatar asked Jul 29 '11 05:07

Bob Ralian


1 Answers

I assume this works because Number is a function.

As shown here: http://jsfiddle.net/zCbdB/1

like image 157
aroth Avatar answered Oct 12 '22 14:10

aroth