Well, returning this
from a standalone function is not much useful, I think it will be useful for you to know how the this
value works:
The this
value is implicitly set when:
When a function is called as a method (the function is invoked as member of an object):
obj.method(); // 'this' inside method will refer to obj
A normal function call:
myFunction(); // 'this' inside the function will refer to the Global object
// or
var global = (function () { return this; })();
When the new operator is used:
var obj = new MyObj(); // this will refer to a newly created object.
And you can also set the this keyword explicitly, with the call
and apply
methods:
function test () {
alert(this);
}
test.call("Hello world");
As you can see, if you make a function call in no-object context (like example 2), the this
value will refer to the Global object, which is not so much useful, unless you are looking for that.
When using function as methods, in object context returning this allows to build patterns of method chaining or fluent interfaces.
On constructor functions, this
is the default return value, if you don't return any other object or you don't even have a return
statement on your function, this
will be returned.