views:

74

answers:

4

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.

+4  A: 

Inside an object, if you have

return this;

as the final line in a method, you can chain method calls one by one, like following syntax:

Foo.doSomething().doSomethingElse().doSomethingCompletelyDifferent();

As each methods return value, is the same object your working on.

Doron
Right on, @Doron.
Upper Stage
A: 

It's used to return the function itself, it is used heavily in libraries like jQuery, for instance, to enable function chaining, ie:

var foo = function1().function2().function3();
Alex
+1  A: 

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:

  1. 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
    
  2. A normal function call:

    myFunction(); // 'this' inside the function will refer to the Global object
    // or 
    var global = (function () { return this; })();
    
  3. 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.

CMS
+1 - beat me to it!
Russ Cam
A: 

If that is the entire contents of the function, it does indeed look pretty useless. If that's just the tail end of the function, then as Doron says, it is useful for chaining.

I'd look at where it's called. It may be that it's some clever little trick.

Usually when you see useless looking code -- like "x=x+0" or "if (flag) flag=true" or that sort of thing -- it's a sign of either code that was edited carelessly, or there was a confused programmer. But sometimes it really does do something strange but useful. The only way to know is to study the context. Of course if your code is so obscure that others must study the context to figure it out, you probably should use clearer code or at least document it.

Jay