Karlito
Karlito

Reputation: 51

The Good Parts, Augmenting Types

I have a question reminiscent of JavaScript - The Good Parts: Function prototypes vs Object prototypes.

In particular, on page 33 of "JavaScript: The Good Parts", we have the following:

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

String.method('trim', function () { 
  return this.replace(/^\s+|\s+$/g, ''); 
});


console.log( "foo  ".trim() ); // Not in "JavaScript: The Good Parts" but added for discussion.

What is the purpose of return this; in Function.prototype.method - is it to allow "dot chaining" or "to program in a cascade style" as noted at the top of page 49?

Also, how does the system know that this refers to the string literal "foo " within String.method?

Upvotes: 3

Views: 117

Answers (1)

Lawrence Jones
Lawrence Jones

Reputation: 955

It's to enable the dotchaining, or fluent method of creating multiple methods on an object.

For example...

String
  .method('one', function(){})
  .method('two', function(){})....

Upvotes: 1

Related Questions