can anybody tell me what’s the point if any for a javascript function like this:
function f() { return this; }
Note: I am trying to improve my javascript skills and found that looking at other people’s code is very good. I bumped into the above one and could not work out its point.
Well, returning
thisfrom a standalone function is not much useful, I think it will be useful for you to know how thethisvalue works:The
thisvalue is implicitly set when:When a function is called as a method (the function is invoked as member of an object):
A normal function call:
When the new operator is used:
And you can also set the this keyword explicitly, with the
callandapplymethods:As you can see, if you make a function call in no-object context (like example 2), the
thisvalue 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,
thisis the default return value, if you don’t return any other object or you don’t even have areturnstatement on your function,thiswill be returned.