importerexporter
importerexporter

Reputation: 19

Augmenting the basic types (from JavaScript: The Good Parts) - why is the value of 'this' returned?

On page 33 the author shows a trick to avoid typing 'prototype' when adding new methods to the basic types, followed by an example that extracts the integer portion of a number.

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this; // removal of this line still yields the same result
};

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

console.log((-10 / 3).integer());

The output is -3 as expected, even if I comment out the line that returns this. What does this line accomplish?

Upvotes: 0

Views: 27

Answers (1)

Quentin
Quentin

Reputation: 943548

It returns the prototype object when you call Number.method(...) which would allow you to chain it: Number.method(...).method(...).

Since your code ignores the return value when you call the method method, changing that return value has no effect.

Upvotes: 1

Related Questions