i wonder, what does “return this” do within a javascript function, what’s its purpose?
supposing we have the following code:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
What does “return this” do inside of a function?
I know what code above does, and what is the use of “this” keyword. I just don’t know what “return this” does inside of a function.
It refers to the object instance on which the method is currently being called. It’s used for chaining. For example, you could do something like this:
Since
fooreturnsthis(a reference tomyObject),barwill be called on the object too. This is the same thing as doingBut requires less typing.
Here is a more complete example:
http://jsfiddle.net/jUfdr/