Nice details, complementary types

I have a question that resembles JavaScript - Good Parts prototypes: Function vs Object .

Specifically on page 33 of "JavaScript: The Good Parts" we have this:

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 returning this: in Function.prototype.method , to allow "chain of dots" or "cascading style programming" noted at the top of page 49?

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

+3


source to share


1 answer


This is to enable a point or loose way of creating multiple methods for an object.

For example...



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

      

+1


source







All Articles