3

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?

Community
  • 1
  • 1
Karlito
  • 51
  • 2
  • 1
    _this_ always refers to the word to the left of the dot which is to the left of the method name, unless you use call/bind/apply. note that if there is no dot and thus no word to the left of the dot, then you can pretend that "window." was there, and then _this_ refers to window. methods called as prototypes are slightly different because _this_ refers to the instance, not the whole prototype object, but that's because the method pretends to be "own"ed by the instance. – dandavis Oct 22 '14 at 19:55
  • Please note that Douglas Crockford has yet to produce a document or presentation where he does "Classical inheritance" correctly. He's worried about having privates for encapsulation and then breaks encapsulation by modifying objects he doesn't own with arbitrary methods. Claims the Parent constructor can't be re used and creates an instance of Parent to be used as Child.prototype. More info about constructor functions and prototype here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Oct 22 '14 at 23:45

1 Answers1

1

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(){})....
Lawrence Jones
  • 955
  • 6
  • 14