i wonder, what does \"return this\" do within a javascript function, what\'s its purpose? supposing we have the following code:
Function.prototype.method = f
tl;dr returning this from a method is a common way to allow "chaining" of methods together.
this refers to the current context, and changes meaning depending on the manner in which you're invoking a function.
With function invocation,
thisrefers to the global object, even if the function is being invoked from a method, and the function belongs to the same class as the method invoking it. Douglas Crockford has described this as "mistake in the design of the language" [Crockford 28]With method invocation,
thisrefers to the object on which the method is being invoked.With apply invocation,
thisrefers to whatever you set it to when calling apply.With constructor invocation,
thisrefers to the object that is created for you behind the scenes, which is returned when the constructor exits (provided you don't misguidedly return your own object from a constructor).
In your example above, you're creating a new method called method that allows you to add functions dynamically, and returns this, thereby allowing chaining.
So you could do something like:
Car.method("vroom", function(){ alert("vroom"); })
.method("errrk", function() { alert("errrk"); });
and so on.