5

I have been reading "javascript: the good part".

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

Example usage is:

Number.method('integer', function () {
    return Math[this < 0 ? 'ceiling' : 'floor'](this);
});
document.writeln((-10 / 3).integer()); // -3

Two questions:

  1. "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." What does that mean? So it saves typing ".prototype.integer"? Doesn't seem to be super important.

  2. We augmented Function.prototype, which sounds it's specific to functions. Number is a native type, should we have augmented Object.prototype instead?

4
  • 1
    Number is a constructor, which means it is actually a function :-)
    – gen_Eric
    Oct 4, 2013 at 18:53
  • 1
    1) Yes. Developers are lazy.
    – Kerry Liu
    Oct 4, 2013 at 18:54
  • Personally, I would prefer to write: Number.prototype.integer = function(){};. I think that's more obvious what you are doing.
    – gen_Eric
    Oct 4, 2013 at 18:57
  • Thanks. I was reading the book and had exactly the same question. Jan 18, 2015 at 8:08

2 Answers 2

3
  1. Yes. It's a rather silly example in that regard.

  2. Keep in mind that Javascript types are functions (e.g, typeof Number == "function"), and this will make much more sense.

1
  • 1
    Oh, OK, so Number here is actually a constructor function that makes a number. Therefore it is linked to Function.prototype. Oct 4, 2013 at 20:19
1
  1. I am currently reading the same book and that seemed a bit weird to me too. I think the whole point of this is to give an example of how altering Function's prototype can be used.
  2. You could eventually alter Object.prototype. But then, it would be higher up the prototype chain, and it would take more time to look it up. The whole point of the "method" is add method's to given constructor's prototype. Thus adding it to Function's prototype makes much more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.